Object gets stuck when trying to bounce off screen

2019-03-05 03:46发布

问题:

public class AsteroidMovement : MonoBehaviour
{

public Vector2 speed;
public Vector2 direction;
private Vector2 movement;

private Vector3 TopScreenBound;
private Vector3 BottomScreenBound;

// Use this for initialization
void Start()
{
    TopScreenBound = Camera.main.ViewportToWorldPoint(new Vector3(0f, 1f, 0f));
    BottomScreenBound = Camera.main.ViewportToWorldPoint(new Vector3(0f, 0f, 0f));
}

// Update is 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 am trying to have asteroids in my game bounce off the edge of my screen and I have got it working decently, but after a few bounces, the asteroid/object gets "stuck" in the wall and glitches out the playing area.

Am I going about this wrong? I cannot see where in the code its making the asteroids stuck after a couple of bounces.Thanks in advance :)

回答1:

You must fix your object's position to bounce inside the screen, if your object is already outside of the screen and it does not fully enter in screen space in the next frame, then your object is changing it's direction infinitely until it enters or leaves the 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;
}