Home > other >  Ways to make a character turn 180 degrees upon hitting collider
Ways to make a character turn 180 degrees upon hitting collider

Time:11-12

this is my first question on StackOverflow, please pardon and fix me if I ask something inappropriate.

I was creating a basic animated scene, where my GameObjects (Which are a couple of pre-animated animals) are running throughout the scene.

Here is the script:

using UnityEngine;
using System.Collections;

public class Locomotion : MonoBehaviour
{
    void Update()
    {
        transform.Translate(Vector3.forward * Time.deltaTime);
    }
}

Now my question is, how can I make them turn 180 degrees around when they hit a collider? Any modification to my existing code is welcomed

CodePudding user response:

I mostly agree with the fine gentleman in that you should use a Rigidbody component to move your animals. Something like this:

using UnityEngine;
using System.Collections;

public class Locomotion : MonoBehaviour
{

    public RigidBody rb;    

    void FixedUpdate()
    {
        rb.velocity=Vector3.forward;
        //or you could use rb.AddForce(Vector3.forward)
        //but in simple cases such as this one it's not necessary
    }
}

Be sure to call all physics calculations from FixedUpdate and not Update, because it you don't your objects can "jitter" in the scene (not going into detail on that).

About the collision detection and the 180:

To detect collisions you have to have a RigidBody component on your objects, as well as a Collider on your objects, as well as on the walls you want to collide with. The way you check for collisions:

using UnityEngine;

public class Test : MonoBehaviour
{
    public Rigidbody rb;

    void FixedUpdate()
    {
        //this is the part that moves your animals,
        //i use transform.forward instead of Vector3.forward because this way
        //it will point in the forward direction of the animal, even if i rotate it
        rb.velocity = transform.forward;
    }

    private void OnCollisionEnter(Collision collision)
    {
        //i tagged the walls i want to turn back the animals as "wall" in the unity editor
        //and here i check if the thing i collided with is a wall
        if (collision.gameObject.CompareTag("wall"))
        {
            //this line basicly says: look in the direction that is currently behind you
            transform.rotation = Quaternion.LookRotation(transform.forward * -1);
        }
    }
}
  • Related