Home > Software engineering >  the ball does not reverse direction
the ball does not reverse direction

Time:08-12

My last "if" is not working, I was using Transform.Translate but due to collision errors, I switched to RigidBody.velocity, now this last "if" I was using with Translate is not even showing when I use Debug .Log. PointR and PointL are limiters for the ball and when the ball gets close to them, it has to change direction. Thanks for the answers.

  public class Ball : MonoBehaviour
{
    public bool isRight;
    public float speed;
    public Transform pointR;
    public Transform pointL;
    Rigidbody2D rb;
   
    
    
void Start()
    {
      rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if(isRight)
        {

        rb.velocity = new Vector2(speed, 0* Time.deltaTime);
      
        }

        else
        {
            rb.velocity = new Vector2(-speed, 0* Time.deltaTime);
     
        }
         if(Input.GetMouseButtonDown(0))
        {
            isRight = !isRight;
        }
        if(Vector2.Distance(transform.position, pointL.position) < 0.1f || Vector2.Distance(transform.position, pointR.position) < 0.1f)
        {
            isRight = !isRight;
            Debug.Log("changed direction");
        }

    
    }
}

CodePudding user response:

If your object is too fast Vector2.Distance will not be less than 0.1f since Vector2.Distance has no negative outputs. Your objects can overcome the distance without getting into the 0.1f range.

I suggest to use triggers that collide with the rigidbody.

It would also be a tip to move rigidbody velocity changes to the fixedupdate method, which is more accurate in physics detections.

  • Related