- Home /
AddForce to object using OnCollisionEnter?
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);
}
}
Answer by Key_Less · Jun 26, 2015 at 01:03 AM
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.
Answer by CalvinAMi · Jun 26, 2015 at 02:12 AM
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);
}
}
}
Hmmmm..... This solution works well enough for objects with a Rigidbody, but not at all really for my intended purpose of utilizing this as a trampoline and having my Player with a Character Controller jump on it. The results are nutty to say the least. I tried adding a Rigidbody and sphere collider to my player in addition to its Character Controller (my Player is a sphere shape).
Any tips on how to edit this script to look for my Player's "whatever" ins$$anonymous$$d of the Rigidbody?
Thanks again for reading and helping =)
Your answer
Follow this Question
Related Questions
RigidBody2D - AddForce - KnockBack Effect. 1 Answer
When to use OnCollisionEnter and OnTriggerStay and how to use rigidbody.AddForce 1 Answer
Rigidbody not calling OnCollisionEnter 1 Answer
How to get Animator.GetBool to work as a parameter in OnCollisionEnter in Unity (c#)? 0 Answers
AddForce not working on Rigidbody2D. 1 Answer