- Home /
Hello, im still kinda new. I finished the simple coding for movements such as jumping and moving but i still cant seem to make my character look at the direction it's moving at. Any help?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class MovementPlayer : MonoBehaviour { [SerializeField] public float moveforce = 10f;
[SerializeField]
public float jumpForce = 11f;
private float movementX;
[SerializeField]
public Rigidbody2D myBody;
private SpriteRenderer sr;
private float direction = 0f;
private Animator anim;
private string WALK_ANIMATION = "idle";
private bool isGrounded = true;
private string GROUND_TAG = "Ground";
private Vector3 moveDirection;
private object rb;
private void Awake()
{
myBody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
sr = GetComponent<SpriteRenderer>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
PlayerMoveKeyboard();
PlayerJump();
}
private void FixedUpdate()
{
PlayerJump();
}
void PlayerMoveKeyboard()
{
movementX = Input.GetAxisRaw("Horizontal");
// Debug.Log("move X value is: " + movementX);
transform.position += new Vector3(movementX, 0f, 0f) * Time.deltaTime * moveforce;
}
void AnimatePlayer()
{
// we are going to the right side
if (movementX > 0)
{
anim.SetBool(WALK_ANIMATION, true);
sr.flipX = false;
}
else if (movementX < 0)
{
// we are going to the left side
anim.SetBool(WALK_ANIMATION, true);
sr.flipX = true;
}
else
{
anim.SetBool(WALK_ANIMATION, false);
}
}
void PlayerJump()
{
if (Input.GetButtonDown("Jump") && isGrounded)
{
isGrounded = false;
//Debug.Log("Jump pressed");
myBody.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag(GROUND_TAG))
{
isGrounded = true;
}
}
} //class ,
Comment
Answer by Narc0t1CYM · Feb 24 at 04:17 PM
I think your code should work, but you aren't calling AnimatePlayer()
in any of your code :)
Call it from Update()
after the PlayerMoveKeyboard()
method