I have watched a bunch of tutorials about this and read the manual concerning onCollisionEnter and onTriggerEnter, however I still can’t figure out what should be a very straightforward task.
All I want is to detect when two instantiated objects touch each other and add a point to the score.
Both objects have rigid bodys, one is kinematic because I don’t want physics to move it. I am detecting for both onCollisionEnter and onTriggerEnter because I really don’t know which one I should be using here.
This is the code I have. I have it attached to the camera. When I play the game, no matter how many spheres contact the target and bounce off, the points variable never changes.
public int points = 0;
void OnCollisionEnter(Collision col)
{
points += 1;
}
void OnTriggerEnter(Collider other)
{
points += 1;
}
void Update()
{
//create sphere
GameObject sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
//add a rigidbody
Rigidbody spheresRigidBody = sphere.AddComponent<Rigidbody> ();
//here I calculate a vector 3 and use AddForce to shoot the sphere,
//I am using a rigid body and an AddForce because I want the sphere
//to arc in a natural way effected by physics
//to keep this short I won't include all that
//create target
GameObject target = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
//add rigid body and make kinematic (don't want target falling)
Rigidbody targetRigidBody = target.AddComponent<Rigidbody> ();
targetRigidBody.isKinematic = true;
}
P.S. I shouldn’t add it to you Camera as the camera has nothing to do with it.
Make an empty gameobject and attach it to that but thats just what I would do
I don’t understand. If I don’t want to use tagging, then what would I put in the if statement?
Also, changing isTrigger = true on the target results in the spheres passing right through. I’d like to keep them bouncing off if they hit. Does that mean I’ll have to use OnCollisionEnter?
If you don’t want to use tagging you should declare a variable for the target and put that in.
If you want to let them bounce well I don’t know how to keep that going as OnTriggerEnter and OnCollisionEnter means that if they enter something happens so sorry
“points” was declared in the first script. If I declare it again in targetColScript, won’t it be a different variable then? So then there will be 2 global variables named “points”?
The only other question I have is how can I test to make sure that the collision is between the sphere and the target? I would assume that if one sphere collided with another sphere that OnCollisionEnter() would still fire and +1 points, which I don’t want.
OnCollisionEnter (Collision col) detects all (and only) the collisions involving the gameObject who owns the script. If other objects can hit your target, you can check the Collision parameter (i.e.: col.gameObject.name or col.gameObject.tag).