- Home /
Speed Boost using OnTriggerEnter
Hi, I'm pretty new to Unity so this may sound like a dumb question, but I'm stuck. Currently I am working on a simple block racing game, that uses a constant force to push the block forward. I want to create an area on the map which would give the player a speed boost while in the area (kinda like the arrows on the ground in Mario Kart). I figured I could do this by creating an empty game object, giving it a box collider, and writing OnTriggerEnter() script, so that when the player enters that zone, the force and therefore the speed of the player will increase. The problem isn't that the player doesn't speed up, it's that the boost activates at the start of the level, not when the player collides with the game object that is the speed boost area. Here is the code I used (in C#).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class speedBoost1 : MonoBehaviour {
public GameObject Player;
private PlayerMovement otherScriptToAccess;
public float boostAmount = 2000f;
// Use this for initialization
void Start ()
{
}
private void OnTriggerEnter(Collider other)
{
//accesses the script that stores the forces acting on the player
otherScriptToAccess = Player.GetComponent<PlayerMovement>();
//accesses the variable in that script called forwardForce
otherScriptToAccess.forwardForce = otherScriptToAccess.forwardForce + boostAmount;
Debug.Log("BOOST!");
}
void OnTriggerExit(Collider other)
{
otherScriptToAccess.forwardForce = otherScriptToAccess.forwardForce - boostAmount;
Debug.Log("normal");
}
// Update is called once per frame
void Update () {
}
}
Any help would be much appreciated!
Answer by Iarus · May 30, 2018 at 01:50 AM
In the OnTriggerEnter, the 'other' variable is the thing that just entered your speed boost zone. You are meant to verify if this object is a thing that you want to give a boost to or not. And then apply a force to it.
What you are doing is "as soon as something touches me whatever it might be, boost the player." If you debug your game and put a breakpoint at the beginning of the method and inspect the value, you'll probably see that 'other' is the racing track or something like that.
Your answer
Follow this Question
Related Questions
Did triggers inside loaded gameobjects break in a recent update? 0 Answers
Is there any way to see exactly which triggers are overlapping? 1 Answer
How to enable passing through collider if speed is high enough at collision point 0 Answers
On Trigger Enter just triggers once for same object 1 Answer
Problem: One Trigger activating a seperate Trigger it is not in contact with. 1 Answer