I would like to change the float “Speed” value to the player´s x velocity but my code does not work help?
Here´s the player moving in the x axis and the Speed float of the animator in the right.
public float acceleration;
public bool isGrounded = true;
public float jumpHeight;
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent();
}
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.Space) && isGrounded == true){
GetComponent().velocity = new Vector2 (0 , jumpHeight);
isGrounded = false;
}
if(GetComponent().velocity.y == 0){
isGrounded = true;
}
anim.SetFloat(“Speed”, Mathf.Abs(GetComponent().velocity.x));
if(Input.GetKey(KeyCode.D)){
transform.position += new Vector3 (acceleration * Time.deltaTime , 0.0f, 0.0f);
transform.localScale = new Vector3 (5,5,5);
}
if(Input.GetKey (KeyCode.A)){
transform.localScale = new Vector3 (-5,5,5);
transform.position -= new Vector3 (acceleration * Time.deltaTime , 0.0f , 0.0f);
}
}
}
I believe the reason the Speed value in your animator is always zero is because your not actually adding any Forces to your RigidBody2D, you’re just moving its position around.
Instead of doing this :
transform.position += new Vector3 (acceleration * Time.deltaTime , 0.0f, 0.0f);
Try something like this for moving to the Right :
GetComponent<RigidBody2D>().AddForce(acceleration);
And moving Left :
GetComponent<RigidBody2D>().AddForce(-acceleration);
Note that this code should be in the FixedUpdate method. A nice way to handle this (from my experience) is to hold a vector2 field that is updated in the normal Update() method and apply it to the RigidBody2D in FixedUpdate(). So something like this :
public float acceleration;
public bool isGrounded = true;
public float jumpHeight;
private bool doJump;
Animator anim;
RigidBody2D rBody2D;
Vector2 velocity;
// Use this for initialization
void Start ()
{
anim = GetComponent<Animator>();
rBody2D = GetComponent<RigidBody2D>();
}
// Update is called once per frame
void Update ()
{
if(Input.GetKey(KeyCode.Space) && isGrounded == true)
{
doJump = true;
isGrounded = false;
}
if(rBody2D.velocity.y == 0)
{
isGrounded = true;
}
if(Input.GetKey(KeyCode.D))
{
velocity.x += acceleration * Time.deltaTime;
transform.localScale = new Vector3 (5,5,5);
}
if(Input.GetKey (KeyCode.A))
{
velocity.x -= acceleration * Time.deltaTime;
transform.localScale = new Vector3 (-5,5,5);
}
if(!Input.GetKey(KeyCode.D) && !Input.GetKey (KeyCode.A))
{
velocity.x = 0;
}
anim.SetFloat("Speed", Mathf.Abs(velocity.x));
}
void FixedUpdate()
{
rBody2D.AddForce(velocity);
if (doJump)
{
rBody2D.AddForce(new Vector2(0, jumpHeight));
doJump = false;
}
}
}
This is pseudo code. its probably not going to work right. Don’t just copy and paste it
2 Likes
Thank you SOOOOO much im 16 i am learning by myself but sometimes i get stuck in stupid errors thank god there is people like you that help newbies
Again thank you!