How to make SKSpriteNode reappear on the opposite side of its SKScene?

♀尐吖头ヾ 提交于 2019-12-09 22:36:56

问题


I have been experimenting with SpriteKit for some time now, and I would appreciate some “best practice” input regarding the movement of my SKSpriteNode within its SKScene’s bounds.

Using the accelerometer, I am applying forces on an SKSpriteNode's PhysicsBody property in order to move the node around the screen in a marble-like fashion. Currently, I set the PhysicsBody of my scene using self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame] so that the marble simply bounces off of my scene's edges.

Instead of bouncing off of my scene's edges, I was hoping that once the marble moved beyond my scene’s bounds (1) it would reappear with the same velocity on the opposite side of my scene (2). I also want this bounds wrapping to occur immediately and in such a way that when any portion of the marble has moved outside of my scene’s bounds (3), that portion will have become visible on the opposite side of the scene (4).

Is it possible to accomplish this while using a single SKSpriteNode and preserving that node’s PhysicsBody?

Thanks in advance!


回答1:


Nope. You need 4 sprite nodes if the sprite can leave the screen in any direction to avoid the sprite from merely "popping" in and out when switching sides. You will have to synchronize their positions and velocities by choosing one of the 4 sprites to be the "master" sprite.

The other three are merely there to represent the sprite visually along the screen edges as well as picking up physics contacts (this may be tricky because each one of the nodes can contact, and all 4 may make the same contact at once). Otoh it may not even be necessary to give the other three physics bodies depending on what other bodies there are to collide with. Simply because the "slaves" might always collide if the master would collide too, but this is only true if other bodies use the same mechanism or collisions never occur near the screen borders.

You would offset the 3 copies by +width, +height and +width+height of the scene size and recalculate this offset every frame based on the master sprite position. And you will have to change the master sprite position when it actually leaves one side of the screen. For instance when the master sprite leaves the right side of the screen you would subtract (not set!) the width of the scene size from its x position.



来源:https://stackoverflow.com/questions/24111042/how-to-make-skspritenode-reappear-on-the-opposite-side-of-its-skscene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!