- Home /
How to make moving backwards slower than moving forwards
Hi, I'm currently using this (slightly adapted) PlayerController script which I copied from here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float movementSpeed = 9.0f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;
var z = Input.GetAxis("Vertical") * Time.deltaTime * movementSpeed;
transform.Rotate(0, x, 0);
transform.Translate(0, 0, z);
}
}
I'd like to make the movement speed when moving backward into say 70% of normal.
I tried using an if statement on z saying that if z<0, z=0.7*z, but that didn't seem to work since apparently z was a double which couldn't be turned into a float without a cast. I didn't want to cast since (according to MS) "Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. "
Anyone know how to solve this?Thanks in advance!
You should be changing movementspeed in the if statement not "z". so, if(z < 0) { movementspeed = (what ever you want) } else{ movementspeed = (forward speed you want) }
Since the value of z is derived from a calculation that already used movementSpeed, changing movementSpeed at this point would not do much of anything.
$$anonymous$$y recommendation would be to store the value of the Input.GetAxis("Vertical") command in a temporary variable, then modify the rest of the calculation based on that being positive or negative. Something like this...
var tmp = Input.GetAxis("Vertical");
var z = tmp * Time.deltaTime * ((tmp < 0 ? .7 : 1) * movementSpeed);
Really don't worry about casting the double to a float; unless the double value goes beyond the float value range, you won't really lose anything.
And since they're both numerical types, the conversion definitely will succeed.
Z in your code is not a double. A very common error is to forget to add the "f" ( 0.7 versus 0.7f)
I believe I did forget just that. Only been using C# for a couple of days, thanks for pointing that out - I never would have realized it otherwise!
Answer by Ginxx009 · Jan 02, 2018 at 03:23 AM
This might help you . My suggestion is using by KeyCode
Vector3 temp = Vector3.zero;
void Update(){
if (Input.GetKey (KeyCode.W)
{
//movementSpeedForward here
temp += transform.forward;
}
if (Input.GetKey (KeyCode.S))
{
//movementSpeedBackward here
temp += transform.forward * -1;
}
}
Hope it helps you :). Its much better :)
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
How do i maintain the same speed in the air? 1 Answer
My character moves when i dont want to 0 Answers
Help with a character movement script? 1 Answer
Multiple Cars not working 1 Answer