I’m trying to make a character move when a key is pressed and stopped when the key is release, the script works, but sometimes (i.e. not always), for some reason, the speed do not return to 0 and the character continue to move after the key is release, call me a perfectionist, but i don’t want players do not stop when they need to, it need to be reliable.
Here is the code:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class CharacterPlus : NetworkBehaviour {
private Rigidbody2D rb2d;
void Start () {
if (isLocalPlayer) {
rb2d = this.GetComponent<Rigidbody2D>();
}
}
void Update()
{
Debug.Log ("Normal Velocity: "+rb2d.velocity+" Inertia Debug: "+rb2d.inertia);
}
// Update is called once per frame
void FixedUpdate () {
//input_x = Input.GetAxisRaw ("Horizontal");
//input_y = Input.GetAxisRaw ("Vertical");
if (isLocalPlayer) {
if (Input.GetKeyDown (KeyCode.D) || Input.GetKeyDown (KeyCode.RightArrow)) {
Move (18f, 0.0f);
}
else if (Input.GetKeyDown (KeyCode.A) || Input.GetKeyDown (KeyCode.LeftArrow)) {
Move (-18f, 0.0f);
}
if (Input.GetKeyDown (KeyCode.W) || Input.GetKeyDown (KeyCode.UpArrow)) {
Move (0.0f, 18f);
}
else if (Input.GetKeyDown (KeyCode.S) || Input.GetKeyDown (KeyCode.DownArrow)) {
Move (0.0f, -18f);
}
if (
Input.GetKeyUp (KeyCode.D) || Input.GetKeyUp (KeyCode.RightArrow) ||
Input.GetKeyUp (KeyCode.A) || Input.GetKeyUp (KeyCode.LeftArrow) ||
Input.GetKeyUp (KeyCode.W) || Input.GetKeyUp (KeyCode.UpArrow) ||
Input.GetKeyUp (KeyCode.S) || Input.GetKeyUp (KeyCode.DownArrow)
) {
Stop ();
}
}
}
void Move(float h,float v){
Vector3 movement = new Vector3 (h,v, 0f);
rb2d.AddForce (movement*70);
}
void Stop() {
rb2d.velocity = Vector3.zero;
rb2d.inertia = 0f;
}
}
Any question, comment, idea or request for clarification would be much apreciated too.
Thanks in advance