Help "Boost" or "Dash" a rigid body ball.

First time scripting really. Movement is from an example script and works just fine. Would like to get an input.getkeydown to boost the ball at a publicly variable speed IN THE SAME direction that the ball is traveling, as defined by getaxis. I can addforce with another vector3 but obviously doesn’t get the desired effect.

C#

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    public float speed;
	public float boost;
   
    void FixedUpdate ()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
       
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
           
        rigidbody.AddForce(movement * speed * Time.deltaTime);
		
		if(Input.GetKeyDown(KeyCode.LeftShift))
	{
				
		rigidbody.AddForce(movement * boost * Time.deltaTime);
       
    }
}
}

Also, would “invoke” be the best way to define a delay until the player can boost again?

Thanks.

That statement seems to contradict itself. The direction the ball is travelling is rigidbody.velocity, and getaxis defines the direction of the player input. Use whichever one you want, but it seems like the vector defined by the input axes would be more appropriate. I would use something like:

 rigidbody.AddForce(movement * boost, ForceMode.Impulse);

You also can’t poll Input.GetKeyDown() from FixedUpdate(). The value is refreshed every Update() so you will not reliably catch key presses. You can use Input.GetKey() safely inside FixedUpdate().

You could use invoke to flip a bool in a certain amount of time to reactivate boost. I don’t think that would be substantially better or worse than using a counter. Either should work.

Does this code help at all? It’s someone elses code that I use for a simple dash. Maybe something in here can help you out.

public var dashDistance : float = 25.0;
private var counter = 0;
private var isDashing = false;
 
function Update()
{
var controller : CharacterController = GetComponent(CharacterController);
 
if(Input.GetKeyDown(KeyCode.E))
{
isDashing = true;
}
if(isDashing){
var forward : Vector3 = transform.TransformDirection(Vector3.forward);
var curSpeed : float = 1 * dashDistance;
controller.SimpleMove(forward * curSpeed);
 
counter++;
}
if(counter > 500){
isDashing = false;
counter = 0;
}
}
1 Like

YES, works great. Thank you much kind sir. :slight_smile:

Thank you! That’s for a character controller but looks useful. Into the archives and I’ll be playing around with it!

Thanks once again peeps, much appreciated.