0

In the game I'm developing, the player moves left and right avoiding obstacles that fall from above, but when the player reaches the left or right limit, a collision bug may occur and he simply leaves the screen. I'm using the rigidbody.velocity and the trigger to check for collision but even so, there are times when it manages to cross the wall. Here the script.(And I'm not using FixedUpdate because it's not responding well when I tap the screen.)

    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

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

    // Update is called once per frame
    void Update()
    {
       

        if(isRight)
        {

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

        else
        {
            rb.velocity = new Vector2(-speed, 0);
     
        }
         if(Input.GetMouseButtonDown(0))
        {
            isRight = !isRight;
        }

        
        

        

        
       

    
    }
    void OnTriggerEnter2D(Collider2D collider)
    {

        if(collider.CompareTag("ColisorEs"))
        {
            
            isRight = !isRight;
        }
          if(collider.CompareTag("colisorR"))
        {
            isRight = !isRight;
        }
    }
        
    
        

      
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
NIK 444
  • 23
  • 5
  • I forgot to mention, there are 2 colliders one on the left and one on the right and both have the Is Trigger activated, thanks for the answers. – NIK 444 Aug 12 '22 at 17:42
  • Please use the correct tags! Note that [`[unityscript]`](https://stackoverflow.com/tags/unityscript/info) is or better **was** a custom JavaScript flavor-like language used in early Unity versions and is **long deprecated** by now. – derHugo Aug 25 '22 at 14:36

1 Answers1

0

Rigidbody changes should be handled in the FixedUpdate methode. It's better for Unitys Physics.

You can leave your Input.GetMouseButtonDown in Update.

Fylus
  • 16
  • 3