- Home /
How can I increase the speed of the player when they run into an object?
I'm making a simple racing game and part of the game is running into certain objects that will increase your speed, but I can't get the speed to change. Here's what I have for code:
using UnityEngine;
using System.Collections;
public class P1Move : MonoBehaviour {
public float speed;
public float increaseSpeed;
private Rigidbody rb;
private Vector3 movement;
private float actualInc;
private bool spdUp = false;
void Start()
{
rb = GetComponent<Rigidbody>();
actualInc = speed * increaseSpeed;
}
void FixedUpdate()
{
if (spdUp == false)
{
float h = Input.GetAxisRaw("HorizontalP1");
float v = Input.GetAxisRaw("VerticalP1");
Vector3 movement = new Vector3(h, 0, v);
rb.AddForce(movement * speed);
}
if (spdUp == true)
{
float h = Input.GetAxisRaw("HorizontalP1");
float v = Input.GetAxisRaw("VerticalP1");
Vector3 movement = new Vector3(h, 0, v);
rb.AddForce(movement * actualInc);
}
}
void onTriggerEnter (Collider other)
{
if (other.tag == "SpdUp")
{
spdUp = true;
}
}
}
Answer by bromley · May 11, 2016 at 07:11 PM
in those objects, create a box collider and insert in a script this function:
void OnTriggerEnter ()
{
your_player_speed_script_name speedPlayer = GameObject.Find ("your player name").GetComponent<your_player_speed_script_name> ();
speedPlayer.SpeedUp ();
}
where your_player_speed_script_name is the name of the script that allow movement on your player, speedPlayer is an arbitrary name string, and *SpeedUp()*is a public void of your script that allow movement on your player, where you can change the speed
SpeedUp () must be public void, and not void
I understand everything but the public void SpeedUp() What exactly do I put in the function?
if your player moves with the public float speed, then in public void SpeedUp() you can change that float value finally, you can make also a void OnTriggerExit () where your player, when exit from a object, gets back to a normal speed
Okay, it looks like it's working! Thank you for your assistance