So after a lot of research and video watching I am unable to figure out how to set up a trigger using C#. I have a 2d car that I am moving with rigidbody.AddForce (Vector3.right * 6) and when it collides with another car I want to Addforce to the left to slow it down and then play an animation. It’s probably a very simple procedure but I have no clue what I’m doing because this is only my first game. Help would be GREATLY appreciated.
You’ll want to add a script to the GameObject that has the car’s collider, and put your rigidbody.AddForce(Vector3.right * 6) call inside OnCollisionEnter. So:
using UnityEngine;
using System.Collections;
public class Car : MonoBehaviour
{
//...
void Start ()
{
//...
}
void Update ()
{
//...
}
//this function is called every time the collider of the gameobject to which this script is attached...
//...collides with another collider
void OnCollisionEnter(Collision collision)
{
//check if the object we are colliding with is a car
if(collision.collider.tag == "Car")
{
//if so, do something... like adding a force to the right
rigidbody.AddForce(Vector3.right * 6f);
}
}
}
Thank you for the reply but I’m a little confused on a couple things. To start I don’t know what I’m suppose to add the script to; Am I adding it to all cars, the car that’s intended to be my player car, or the cars intended to be the enemy cars. Also i should have mentioned this before but I don’t want my player car to be stopped then add force I want it to just be slowed down by enemy cars. So when it hits a enemy car it will go through it, not be stopped by it. Right now I have my enemy set to trigger but it does nothing when my car goes through it, when I make it not a trigger it stops my player car completely. Lastly I don’t know if this matters but my cars are using box colldiers. I don’t know if that matters or not…
So I took what you gave me, did some adjustments, and it works the way I want. Thank you again for your help.
using UnityEngine;
using System.Collections;
public class Car : MonoBehaviour
{
//this function is called every time the collider of the gameobject to which this script is attached...
//...collides with another collider
void OnTriggerEnter(Collider collision)
{
//check if the object we are colliding with is a car
if(collision.collider.tag == "Car")
{
//if so, do something... like adding a force to the right
rigidbody.AddForce(Vector3.left * 120);
}
}
}