- Home /
applying force ontriggerenter unity c#
Im new to Unity and have been following youtube tutorials to create my first game. I have been searching on the internet for a while now and I cant get any answers to my questions. so what I want to do is create a speed boost for the player but the way I have scripted the player movement seems to be a problem. the way I have scripted it is by following Brackeys tutorial: https://www.youtube.com/watch?v=Au8oX5pu5u4&list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6∈dex=4 Player movement; using UnityEngine;
public class PlayerMovement : MonoBehaviour {
// This is a reference to the Rigidbody component called "rb"
public Rigidbody rb;
public float forwardForce = 2000f; // Variable that determines the forward force
public float sidewaysForce = 500f; // Variable that determines the sideways force
// We marked this as "Fixed"Update because we
// are using it to mess with physics.
void FixedUpdate()
{
// Add a forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d")) // If the player is pressing the "d" key
{
// Add a force to the right
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a")) // If the player is pressing the "a" key
{
// Add a force to the left
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("right")) // If the player is pressing the "right" key
{
// Add a force to the right
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("left")) // If the player is pressing the "left" key
{
// Add a force to the left
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
But what I want to do is to make the player move faster for a short amount of time to be ahead of another player. The way I thought it would work is if I added force through an ontrigger thing but I don't know if this is possible. If I could get some help that would be fantastic! thank you for your time :)
Answer by petarpejovic · Feb 06, 2018 at 06:53 PM
Hi :) First you can instead of using Input.GetKey() for moving left and right, use Input.GetAxis("Horizontal"). And then you can write something like this:
float move = Input.GetAxis("Horizontal"); rb.velocity = new Vector3(move * speed, 0,0);
And now about your bust.
void OnTriggerEnter(Collider coll) { speed += 10f; }
Your answer