- Home /
Ideas for detecting collision speed with trigger?
So basically I have a car flying off a ramp. I want to put a trigger at the top counting the speed of the car. If it is fast enough it will start doing a flip (already scripted the flip :-D ). So any ideas on detecting the speed of the car when it gets to the top of the ramp?
Thanks!
How about using the car's rigidbody's velocity? $$anonymous$$aybe you need to use velocity.sqr$$anonymous$$agnitude to get a float value ins$$anonymous$$d of a vector.
Answer by Yokimato · Apr 04, 2016 at 03:16 AM
Put a BoxColider
component on an empty gameobject (without any mesh) at the top of the ramp. Set the Trigger
to true on that colider.
Attach a new script to that colider which checks for the car and it's speed. Something like...
using UnityEngine;
using System.Collections;
public class RampFlipper : MonoBehaviour {
void OnTriggerEnter(Collider other) {
if(other.gameObject.tag.Equals("Car")) {
Car car = other.gameObject.GetComponent<Car>();
if(car.GetSpeed() >= FLIP_THRESHOLD) {
car.DoFlip();
}
}
}
}
To get the car's speed, you can store the previous position of the car on each Update()
call and then divide it by the Time.deltaTime
. Something like...
private Vector3 previousPosition;
private float speed;
private void Update() {
float distanceSinceLastFrame = Vector3.Distance(transform.position, previousPosition);
speed = distanceSinceLastFrame / Time.deltaTime;
}
public float GetSpeed() {
return speed;
}
Hope this helps.
Answer by emarcotte · Apr 04, 2016 at 04:13 AM
I think I would make a collider, make it a trigger, place it at the top of the ramp, and OnTriggerEnter I would inspect the attachedRigidBody's velocity magnitude, basically as @Cherno describes.