- Home /
How to increase the speed of an object's movement when it enters a trigger?
This is my first Unity3D assignment, and could use some help.
I'm basically making my own Rube Goldberg model, and I want to make the moving sphere speed up when it reaches this roller-coaster loop, as shown in my poorly drawn sketch. For example, when it collides with the green area, it is triggered to speed up so it would have enough momentum to reach the other end.
I can't for the life of me find any tutorials anywhere, and I'm an absolute beginner at programming.
Answer by Magso · Feb 03, 2019 at 01:18 AM
//Speed and acceleration variable
float speed, accel;
void OnTriggerEnter (Collider other)
{
//check if the other collider is tagged as "Area"
if(other.tag == "Area")
{
speed += accel;
}
}
//to move the object you can either use addforce or translate.
void FixedUpdate
{
GetComponent<Rigidbody>().AddForce(0, 0, speed * Time.DeltaTime);
}
//or
void Update
{
transform.Translate(0, 0, speed * Time.DeltaTime);
}
Forgot to mention, this script goes on the ball and the ball needs a trigger collider, the area can be a kinematic rigidbody.
Hey thanks for the help. For some reason when the 'Is Trigger' box on the ball is ticked, the ball fails to collide with anything and simply just goes through all the objects in the scene. Any idea why this might be happening?
The ball would need a second collider that is set as a trigger. Also the area to speed it up would have to be set as a trigger as well to avoid collision with the ball.
There are two ways you can set this whole thing up, either have a single script on the ball (which was my first answer) or have a script for the ball,
float speed;
void FixedUpdate
{
GetComponent<Rigidbody>().AddForce(0, 0, speed * Time.DeltaTime);
}
//or
void Update
{
transform.Translate(0, 0, speed * Time.DeltaTime);
}
And another script for the area.
float accel;
void OnTriggerEnter (Collider other)
{
//check if the collider is tagged as "Player" this time.
if(other.tag == "Player")
{
other.GetComponent<ScriptName>().speed += accel;
}
}
This way the ball doesn't need to have a trigger.
Your answer
![](https://koobas.hobune.stream/wayback/20220612191005im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Adding Speed to onTriggerEntered 1 Answer
Ideas for detecting collision speed with trigger? 2 Answers
Boost Script Time problems 1 Answer
Unity car tutorial speed boost 1 Answer