Object gets stuck when trying to bounce off screen edges, am I doing this wrong?

前端 未结 1 551
执念已碎
执念已碎 2021-01-28 02:20
public class AsteroidMovement : MonoBehaviour
{

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

private Vector3 TopScreenBound;
private Vecto         


        
相关标签:
1条回答
  • 2021-01-28 02:34

    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;
    }
    
    0 讨论(0)
提交回复
热议问题