Hi, very basic scripting question- I have a cube with a trigger script attached to it:
var power : float = 500.0;
function OnTriggerEnter (player : Collider) {
if(player.tag=="Player")
rigidbody.AddForce(Vector3(0,power,0));
}
Instead of the force effecting the trigger cube however, I would like to effect the player. How would I write this?
Thanks!
If the player is a rigidbody, you could write this:
var power : float = 500.0;
function OnTriggerEnter (player : Collider) {
if (player.tag=="Player")
player.rigidbody.AddForce(Vector3(0,power,0));
}
This will produce errors if the player isn’t a non-kinematic rigidbody. If the player is a CharacterController, add the ImpactReceiver script below to it and modify the OnTriggerEnter code a little:
ImpactReceiver.js:
var mass = 3.0; // defines the character mass
var impact = Vector3.zero; // momentum
private var character: CharacterController;
function Start(){
character = GetComponent(CharacterController);
}
// call this function to add an impact force:
function AddImpact(force: Vector3){
if (force.y < 0) force.y = -force.y; // reflect down force on the ground
impact += force / mass;
}
function Update(){
// apply the impact force:
if (impact.magnitude > 0.2) character.Move(impact * Time.deltaTime);
// consumes the impact energy each cycle:
impact = Vector3.Lerp(impact, Vector3.zero, 5*Time.deltaTime);
}
The OnTrigger code should be modified like below:
var power : float = 500.0;
function OnTriggerEnter (player : Collider) {
if (player.tag=="Player")
player.GetComponent(ImpactReceiver).AddImpact(Vector3(0,power,0));
}