Hi,
I was trying to script a player controller in javascript. I have the Input axes set for the WSAD configuration. I now have the following code:
var playerSpeed : float;
function Update ()
{
if(Input.GetAxis(“Vertical”) > 0) // The W key
{
characterController.Move(transform.forward * playerSpeed * Time.deltaTime);
}
if(Input.GetAxis(“Vertical”) < 0) // The S key
{
characterController.Move(transform.forward * -playerSpeed * Time.deltaTime);
}
if(Input.GetAxis(“Horizontal”) > 0) // The A key
{
characterController.Move(transform.right * playerSpeed * Time.deltaTime);
}
if(Input.GetAxis(“Horizontal”) < 0) // The D key
{
characterController.Move(transform.right * -playerSpeed * Time.deltaTime);
}
}
The forward and back code works fine. The sideways code doesn’t. The A key takes me forward, and the D key takes me back. I’ve messed around with all sorts of adjustments to the code, including reversing directions, and checking the input manager. What am I doing wrong?
Thanks
Try using KeyCode instead of get axis for detection.
OK I just tested that out. I wrote this:
if(KeyCode.W)
The thing is that at this point I move forward all the time without pressing the W key. Why would that be?
Thanks
'Cause your current if-statement checks wether a KeyCode.W excists (so,assigned.)
rather use
if(Input.GetKey("w"))
to detect wether it’s active.
Also, be sure to not let the detection of the keypress move the player directly unless you want your character to move in only one direction at a time.
Like also done in the character controller is a quite effective method. example;
float FowardSpeed;
float BackwardSpeed;
float SidewaysSpeed;
Vector3 MoveDirection = 0;
if(Input.GetKey("w"))
MoveDirection += Direction.Forward*ForwardSpeed;
if(Input.GetKey("s"))
MoveDirection += Direction.Forward*BackwardSpeed;
if(Input.GetKey("a"))
MoveDirection += Direction.Left*SidewaysSpeed;
if(Input.GetKey("d"))
MoveDirection += Direction.Right*SidewaysSpeed;
characterController.Move(MoveDirection*Time.deltaTime)
+= is shortcode for “take this value and add this to” just like -= i the opposite.
so a+=b = a+b
CD+= ab = CD+(ab)