Hello, I’m learning C# bit by bit, and I’ve really just started, so I’m trying to write a simplest character control for 2D game now.
Here’s my code:
public Vector2 speed = new Vector2(1,0);
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float inputX = Input.GetAxis ("Horizontal");
float inputY = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (
speed.x = inputX,
speed.y = inputY,
0);
movement *= Time.deltaTime;
transform.Translate (movement);
}
And now I’m trying to multiply the speed by *2 whenever LeftShift is pressed.
I’m adding the following code to the Update() right after the previous code:
if (Input.GetKeyDown(KeyCode.LeftShift))
{
Debug.Log ("Shift is pressed");
movement *= Time.deltaTime;
transform.Translate (movement*2);
}
But it doesn’t work. Neither is
movement *= 2;
I really don’t undestand why’s that, because if I add a multiplier to the original equasion, it works perfectly and the speed is doubled at all times.
int runningSpeed = 4;
movement = movement.normalized * runningSpeed* Time.deltaTime;
transform.Translate (movement);
Try this. Also, I suggest having only one transform.Translate(movement); on the same method. Try putting the transform.Translate(movement); at the last line and under the part where you click the “LeftShift”, you simply edit the runningSpeed to 2 or 4 and edit the movement outside of that “movement = movement.normalized * runningSpeed* Time.deltaTime;” then finally, your transform.Translate(movement) at the last line.
public Vector2 speed = new Vector2(1,0);
int runningSpeed = 1;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float inputX = Input.GetAxis ("Horizontal");
float inputY = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (
speed.x = inputX,
speed.y = inputY,
0);
if (Input.GetKeyDown(KeyCode.LeftShift))
{
Debug.Log ("Shift is pressed");
runningSpeed = 4;
}
movement = movement.normalized * runningSpeed * Time.deltaTime;
transform.Translate (movement);
}
I wouldn’t suggest officially using this code but I think its good for learning.