- Home /
Why isn't my player moving?
I am a beginner with Unity, so I run into a few dumb mistakes, but this problem has left me puzzled. Here's my code:
#pragma strict
var PlayerSpeed : float;
function Start () {
}
function Update () {
if(Input.GetKey (KeyCode.W)){
transform.Translate(0,0,PlayerSpeed);
animation["Player Bob"].wrapMode = WrapMode.Loop;
animation.Play("Player Bob");
}else if(Input.GetKeyUp (KeyCode.W)){
animation["Player Bob"].wrapMode = WrapMode.Default;
animation.Stop("Player Bob");
}
}
When I press W, nothing happens. As you can see, I have an animation. I think that's what's causing my problem, as I've just started to use them today. Oh but the animation plays when I press W. Please help.
:)
Answer by IgorAherne · Jul 21, 2013 at 06:23 AM
You've forgot to tell the PlayerScpeed variable what value it must have. By default it's zero, so although the computer reacts to buttons, your character has 0 forward speed and stays in place :> The following code works (I've simplified it and removed animations, so it's more clear. You can put them back after).
Also, make sure you've attached the script to your player game object.
#pragma strict
var PlayerSpeed : float; //don't forget to assign the value to this guy. Do it here or in Start() or in the inspector for the current script, before you hit play.
function Start () {
}
function Update () {
if(Input.GetKey (KeyCode.UpArrow)){ //changed from W to up arrow, will be working with W as well
transform.Translate(0,0,PlayerSpeed)*Time.deltaTime; //when working with movement in the Update function, add Time.deltaTime, so that the player's speed isn't affected by current FPS.
}
else if(Input.GetKeyUp (KeyCode.UpArrow)){ //changed from W to up arrow, will be working with W as well
Debug.Log("Key Up");
}
}
Okay, thanks for some tips like the Time*deltaTime thing, but I should've probably said that I configured the PlayerSpeed variable in the inspector. So this is not what's causing it. But thanks for the tips anyways.
Your answer
Follow this Question
Related Questions
Can I make animations snap to a frame? 1 Answer
How to stop animated character returning to starting position after animation is complete 3 Answers
Ellipse Animation by code 2 Answers
anim stream problems!! 0 Answers
transform.Translate() problems 1 Answer