- Home /
How to launch the player a certain distance with button press?
I'm trying to implement a mechanic where the player travels a certain distance in the direction of the first person camera by pressing the right mouse button. Currently, the player will only travel for one frame because I'm using GetButtonDown, so I want to extend the travel distance somehow. I've tried using a timer and a while loop to do that, but the player ends up teleporting, and doesn't travel smoothly like I want it to.
private CharacterController _controller;
public Transform camera;
public float bounceSpeed = 5f;
public bool bounceActive;
void Start()
{
_controller = GetComponent<CharacterController>();
bounceActive = false;
}
void Update()
{
Bounce();
}
private void Bounce()
{
Vector3 direction = new Vector3(camera.forward.x, camera.forward.y, camera.forward.z);
if (Input.GetButtonDown("Fire2"))
{
_controller.Move(direction * bounceSpeed * Time.deltaTime);
bounceActive = true;
}
else
{
bounceActive = false;
}
}
Answer by Tejesh4678 · Aug 07, 2021 at 03:45 AM
If u want the player to move if right mouse button is held down then this link might be useful Do something while key is pressed and held down..
If u want the player to move a certain distance once u right-clicked, then remove the if statement in Bounce() and use boolean operator to execute Bounce() method. In update If the player right-clicked then set this boolean to true. If the boolean is true then execute the Bounce() method. Heres an example:
bool moveCharacter=false;
void Update()
{
if(Input.GetButtonDown("keycode"){
moveCharacter=true;
}
if(moveCharacter)
{
Bounce()
}
}
void Bounce()
{
// your code
if(player reached the distance you wanted then)
{
moveCharacter=false;
}
}