c# - Object gets stuck when trying to bounce off screen edges, am I doing this wrong? -
public class asteroidmovement : monobehaviour { public vector2 speed; public vector2 direction; private vector2 movement; private vector3 topscreenbound; private vector3 bottomscreenbound; // use initialization void start() { topscreenbound = camera.main.viewporttoworldpoint(new vector3(0f, 1f, 0f)); bottomscreenbound = camera.main.viewporttoworldpoint(new vector3(0f, 0f, 0f)); } // update called once per frame void update() { if (gameobject.transform.position.y >= topscreenbound.y) { direction.y *= -1; } if (gameobject.transform.position.y <= bottomscreenbound.y) { direction.y *= -1; } movement = new vector2(speed.x * direction.x, speed.y * direction.y); } void fixedupdate() { rigidbody2d.velocity = movement; } }
i trying have asteroids in game bounce off edge of screen , have got working decently, after few bounces, asteroid/object gets "stuck" in wall , glitches out playing area.
am going wrong? cannot see in code making asteroids stuck after couple of bounces.thanks in advance :)
you must fix object's position bounce inside screen, if object outside of screen , not enter in screen space in next frame, object changing it's direction infinitely until enters or leaves screen.
change this:
if (gameobject.transform.position.y >= topscreenbound.y) { direction.y *= -1; } if (gameobject.transform.position.y <= bottomscreenbound.y) { direction.y *= -1; }
to this:
if (gameobject.transform.position.y >= topscreenbound.y) { gameobject.transform.position.y = topscreenbound.y; direction.y *= -1; } if (gameobject.transform.position.y <= bottomscreenbound.y) { gameobject.transform.position.y = bottomscreenbound.y; direction.y *= -1; }
Comments
Post a Comment