The question is answered, right answer was accepted
Script to animation and movement of 2d player
Hi ! I new to game development and I found a tutorial for a script for movement of 2d player, I copied it, my animation works but my player doesn't move, I try to fix it. So this is the original script :
using UnityEngine; using System.Collections;
public class Playermovement : MonoBehaviour {
Rigidbody2D rbody;
Animator anim;
// Use this for initialization
void Start () {
rbody = GetComponent<Rigidbody2D> ();
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (movement_vector != Vector2.zero) {
anim.SetBool ("iswalking", true);
anim.SetFloat ("Input_x", movement_vector.x);
anim.SetFloat ("Input_y", movement_vector.y);
}
else {
anim.SetBool ("iswalking", false);
}
rbody.MovePosition (rbody.position + movement_vector * Time.deltaTime);
}
}
This is the link to the tutorial : https://www.youtube.com/watch?v=XZDjkQ8wEd0&list=PL_4rJ_acBNMH3SExL3yIOzaqj5IP5CJLC∈dex=4
and I try to fix it with replace void Update by void FixedUpdate as explained comments
that is odd it should be at least doing some movement. But you are correct in putting it in FixedUpdate but if you are using FixedUpdate you also need to use Time.fixedDeltaTime
I corected my mistake but I still have the same problem
do you have a Rigidbody2D attached and if so maybe check to see if the constraints are set on it
Answer by Mineck · Aug 29, 2016 at 06:43 PM
Finally, watching other script and trying, I fix my script. I thank you for trying to help me. So this is the new script with correction for those who have the same problem:
using UnityEngine;
using System.Collections;
public class Playermovement : MonoBehaviour {
public float speed = 18;
Rigidbody2D rbody;
Animator anim;
// Use this for initialization
void Start () {
rbody = GetComponent<Rigidbody2D> ();
anim = GetComponent<Animator> ();
}
void FixedUpdate () {
Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"))*speed* Time.fixedDeltaTime;
if (movement_vector != Vector2.zero) {
anim.SetBool ("iswalking", true);
anim.SetFloat ("Input_x", movement_vector.x);
anim.SetFloat ("Input_y", movement_vector.y);
}
else {
anim.SetBool ("iswalking", false);
}
rbody.MovePosition (rbody.position + movement_vector);
}
}
Follow this Question
Related Questions
Movement works in all directions except one? 0 Answers
My 2d movement script isn't working 0 Answers
Spawned game object does not carry the Animator component 0 Answers
Why won't my 2D Sprite Move? 1 Answer
Animation location problem! 0 Answers