Search code examples
unity-game-engine2dmovehit

How should I move my gameObject(box) so as when the box hit another box it stops(or to be more precise, the hit to be registered first)


GameEnvironment is 2d. Physcis none.

I have a gameObject(gO) tagged box that automatically moves from point A to point B. The script attached to this has the ff code:

transform.position = Vector3.Lerp (transform.position, targetPos, (Time.time-startTime)*0.0001f);

Note: this movement is slow.

I also added a raycast2d to it that basically says if it hit another box, it will stop in its current position.

if(hit){
        if (hit.collider.tag == "box") {
            canControl = false;
            canMove = false;
            canSpawn();
        }

} else {
    canMove = true;
}

both this and the code above is in boxMovementScript's Update.

At this point, all is well and good, when I removed a box in front of another box, the latter continues to move towards the targetPos. When a box blocks its way, it stops in its current position.

My problem arises when I try to control the box to move faster. If another box is in front of it, it just bypass the box, and the hit is never registered. My move right code is below. This is in my GameOBjectControllerScript's void Update.

if (Input.GetKeyDown(KeyCode.D) && rX !=-100){
    box.transform.position = Vector3.Lerp(atom.transform.position, rightendpos, 1);
}

the rightendpos here is bascially a vector3 position that is two boxes away from its current position.

How should I move my gameObject(box) so as when the box hit another box it stops?


Solution

  • You can try two things:

    First you can try running the code inside the FixedUpdate() method instead as it's kinder on physics.

    Secondly you can for your moving cube game object add the method OnCollisionEnter2D() in an attached script, more info here http://docs.unity3d.com/ScriptReference/Collider2D.OnCollisionEnter2D.html [OnCollisionEnter page has more examples!] There are a few other collision events too, such as OnCollision2D etc.

    I would try using the OnCollisionEnter2D() to stop any movement, and of course you can try to detect any tags etc, Goodluck!