- Home /
Increase Speed
I'm trying to script a cube where upon going through a bigger cube, it increases speed. Here's my code:
using UnityEngine;
using System.Collections;
public class IncreaseSpeed : MonoBehaviour {
public float speed;
void OnTriggerEnter(Collider other) {
if(other.gameObject.CompareTag("Trigger01")){
rigidbody.AddForce(0,0,speed);
Debug.Log("We've finally touched!");
}
}
}
The console reads the Debug Log "We've finally touched!" so it's detecting collision and the trigger does work.
So why isn't a force being added to the cube? I was thinking maybe it's because I have this in an OnTriggerEnter method and that it's only adding a force to the rigidbody for one frame?
I'd appreciate any assistance. Thank you for your time.
Is is$$anonymous$$inematic check on the game object's RigidBody?
http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody-is$$anonymous$$inematic.html
It wasn't when I posted this. The object still doesn't increase speed whether I have is$$anonymous$$inematic checked or not.
Answer by AlucardJay · Oct 19, 2012 at 11:18 PM
As force is applied over time but OnTriggerEnter only happens once per event, you need to use Impulse Force Mode in your Add Force :
AddForce : http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody.AddForce.html
ForceMode.Impulse : http://docs.unity3d.com/Documentation/ScriptReference/ForceMode.Impulse.html
all ForceModes : http://docs.unity3d.com/Documentation/ScriptReference/ForceMode.html
Replace the Addforce line in your script to :
rigidbody.AddForce( 0, 0, speed, ForceMode.Impulse );
or you may want to use :
rigidbody.AddForce( transform.forward * speed, ForceMode.Impulse );