0
\$\begingroup\$

My player in unity moves but doesn't stop when i let go of the key heres the code:

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

    Vector3 movement = new Vector3();
    public CharacterController player;
    public float speed;
    public float vertSpeed;
    public float gravity;
    // Use this for initialization
     void Start(){

    }
    void Update(){
        PlayerMovement ();
    }
    void PlayerMovement(){



        if (Input.GetKeyDown (KeyCode.Space)) {
            transform.Translate(Vector3.up * vertSpeed * Time.deltaTime, Space.World);
            if (!player.isGrounded) {
                movement.y = movement.y - gravity * Time.deltaTime;
            }
        }
        if (Input.GetKey (KeyCode.A)) { // left
            movement.x = movement.x - speed * Time.deltaTime;

        } else if (Input.GetKey (KeyCode.D)) {// goes right 
            movement.x = movement.x + speed * Time.deltaTime;
        }



        player.Move ((movement * speed) * (Time.deltaTime));
    }

}
\$\endgroup\$
  • 1
    \$\begingroup\$ mark this as answered instead of changing the title. \$\endgroup\$ – Ryan white Aug 17 '16 at 13:58
  • 1
    \$\begingroup\$ How do I do that? \$\endgroup\$ – CodeTipsTutorials Aug 17 '16 at 14:00
  • 1
    \$\begingroup\$ Underneath the answer's vote buttons should be a tick. Just press that. \$\endgroup\$ – Ryan white Aug 17 '16 at 14:00
  • 1
    \$\begingroup\$ I'm on my phone atm I'll be sure to do it soon \$\endgroup\$ – CodeTipsTutorials Aug 17 '16 at 14:02
  • \$\begingroup\$ that would explain the badge for rollbacks haha, thanks :) ill be sure to use this. \$\endgroup\$ – Ryan white Aug 17 '16 at 14:23
4
\$\begingroup\$

As you are using CharacterControllercomponent you don't need to check which individual button pressed. By checking horizontal axis you can get if you are pressing left/A or right/D at once. Also a "Jump" button is defined for Space button in Unity.

Your PlayerMovement() should be like:

void PlayerMovement()
{
    if (player.isGrounded)
    {
        movement = new Vector3(Input.GetAxis("Horizontal"), 0, 0);
        movement = transform.TransformDirection(movement);
        movement *= speed;
        if (Input.GetButton("Jump"))
            movement.y = vertSpeed;

    }
    movement.y -= gravity * Time.deltaTime;
    player.Move(movement * Time.deltaTime);
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.