0
\$\begingroup\$

I want to make object stopped when it hit collider of another object.
But it doesn't stop. How can I fix this? - Unity

my code is:

public class move: MonoBehaviour {
    public float speed = 0.5f;
    // Update is called once per frame
    void Update () {
      if (Input.touchCount ==1)
        {
            Touch touch = Input.GetTouch(0);
            float x = -7.5f + 15 * touch.position.x / Screen.width;
            float y = -2;
            transform.position = new Vector2(x * speed, y);
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Please see this earlier Q&A about moving objects with their transforms. When you use the transform rather than a rigidbody/rigidbody2D to move an object, you're telling Unity that you don't want to use physics simulation & collision detection on that motion, you just want to object to go to the exact point you specified. So Unity obeys. If you want to avoid penetrations with colliders, you need to either move the object with physics to use the built-in collision handling, or perform your own collision checks. \$\endgroup\$
    – DMGregory
    Apr 29, 2018 at 14:08

1 Answer 1

0
\$\begingroup\$

The easiest approach would be: "store the object's old position, update its position, if it is colliding, move it back."
Sadly, in Unity, you cannot determine directly whether or not a collision is happening at the moment. One could implement OnCollisionEnter / OnCollisionExit to set some "colliding" state, but you would need to be careful with synchronisation between moving / checking collision.

\$\endgroup\$
1
  • \$\begingroup\$ This answer would be better if it included tips for how to determine whether the object is colliding, or a sample/sketch of code that does what you describe. \$\endgroup\$
    – DMGregory
    Apr 29, 2018 at 14:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .