How do I AddForce to a static object when it touches another object?
I have a cube on the ground. I have a sphere above it with gravity.
When I press play, I want the sphere to drop and land on the cube.
The cube should repel the sphere upwards.
How far off am I from getting this concept?
public float forceApplied = 500;
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Sphere")
Debug.Log ("Collision!");
{
GetComponent<Rigidbody>().AddForce (0, forceApplied, 0);
}
}
Key_Less !!! This worked perfectly =) Thank you for the excellent help!
Below is my complete script just in case anyone reads this looking for the same type of help.
using UnityEngine;
using System.Collections;
public class Trampoline : MonoBehaviour {
public float forceApplied = 50;
void OnCollisionEnter(Collision col)
{
Debug.Log ("Collision!");
if (col.gameObject.name == "Sphere")
{
col.gameObject.GetComponent<Rigidbody>().AddForce (0, forceApplied, 0);
}
}
}
You’re very close. Based on your code, I’m going to make a couple assumptions. First, I’m assuming that your cube is static (and possibly flagged as Is Kinematic) and the sphere is not, so you aren’t actually adding a force to a static object. Second, I’m assuming this script is attached to your cube, in which case you are getting the rigidbody component that is attached to your static cube (Line 6) and trying to add your force to that.
The Sphere’s Collision class is conveniently passed into the OnCollisionEnter() method once it collides with the cube. So what you want to do instead is add the force to the rigidbody that is attached to the Sphere that has collided with your cube. Try this:
col.gameObject.GetComponent<Rigidbody>().AddForce (0, forceApplied, 0);
Also, your Debug.Log() method (Line 4) is in a strange place. I’d suggest moving it above your ‘if’ statement.