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\$
5
  • 1
    \$\begingroup\$ mark this as answered instead of changing the title. \$\endgroup\$ Commented Aug 17, 2016 at 13:58
  • 1
    \$\begingroup\$ How do I do that? \$\endgroup\$ Commented Aug 17, 2016 at 14:00
  • 1
    \$\begingroup\$ Underneath the answer's vote buttons should be a tick. Just press that. \$\endgroup\$ Commented Aug 17, 2016 at 14:00
  • 1
    \$\begingroup\$ I'm on my phone atm I'll be sure to do it soon \$\endgroup\$ Commented Aug 17, 2016 at 14:02
  • \$\begingroup\$ that would explain the badge for rollbacks haha, thanks :) ill be sure to use this. \$\endgroup\$ Commented Aug 17, 2016 at 14:23

1 Answer 1

3
\$\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); } 
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.