- Home /
about character movement in 8 direction
i am write a javascript in order to control the movement of my character, but i have problem in the movement in the remaining 4 direction, which are top right left and down right left here are part of my code
if(Input.GetKey("w")) {
animation.CrossFade("moving"); //animation
direction = Vector3.forward;
transform.forward = new Vector3(0f, 0f, 1f);
this.transform.position += this.transform.TransformDirection(new Vector3(0, 0, speed)); //turning the character facing direction and move
}
else if(Input.GetKey("s")){
where the remain code is for the down right and left
my problem is that if i continue to use else if (Input.GetKey("w")&&Input.GetKey("d")) it will be useless as it already go into the Input.GetKey("w") or ("d") how should i do?
further more, i would aslo like to ask how can i check for a double click?say click "w" 2 times.
Answer by robertbu · Sep 22, 2013 at 10:34 AM
In order to get 8 directions of movement, you can combine some vectors. Start with a new scene and cube and add this script to the cube:
#pragma strict
var speed = 2.0;
function Update () {
var direction = Vector3.zero;
if(Input.GetKey(KeyCode.A)) {
direction += Vector3.left;
}
if(Input.GetKey(KeyCode.S)) {
direction += Vector3.back;
}
if(Input.GetKey(KeyCode.D)) {
direction += Vector3.right;
}
if(Input.GetKey(KeyCode.W)) {
direction += Vector3.forward;
}
transform.Translate(direction * speed * Time.deltaTime);
}
Alternately you can use GetAxisRaw() to build the vector. "Horizontal" and "Vertical" are by default mapped to the ADWS keys (as well as the arrow keys).
#pragma strict
var speed = 2.0;
function Update() {
var direction = Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
transform.Translate(direction * speed * Time.deltaTime);
}
great!Thank you for your help! then how about checking double click of a key? say pressing ww than my charcter will run
Note for the future, please keep questions to a single issue. As for double click, you can use a timestamp. At the top of the file:
var doubleClickTime = 0.15;
private var timestamp = -1.0;
And then in Update():
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.W)) {
if (Time.time - timeStamp < doubleClickTime) {
Debug.Log("Double click");
}
timestamp = Time.time;
}