MIF_E31230902/Assets/Asset/_Main/Script/CharacterController.cs

99 lines
2.3 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace PahlawanEnergi
{
public class CharacterController : MonoBehaviour
{
//key animator
private const string isWalking_key = "isWalking";
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Animator anim;
//movement
[SerializeField] private float walkSpeed = 5f;
//reduce gerbage collector
private float inputX;
private bool isFacingRight;
private bool lastFacingRight;
private Vector2 newPos;
// Start is called before the first frame update
void Start()
{
isFacingRight = true;
lastFacingRight = true;
}
// Update is called once per frame
void Update()
{
//inputX = Input.GetAxisRaw("Horizontal");
//Debug.Log($"Input X: {inputX}");
if (inputX <= 0.01f && inputX >= - 0.01f)
{
if (!anim.GetBool(isWalking_key)) return;
anim.SetBool(isWalking_key, false);
rb.velocity = Vector2.zero;
}
else
{
//check facing direction
isFacingRight = inputX > 0.1f;
if (isFacingRight != lastFacingRight)
{
SetFacingDirection(isFacingRight);
}
//set animation
anim.SetBool(isWalking_key, true);
//set movement
//newPos = rb.position + Vector2.right * inputX * walkSpeed * Time.fixedDeltaTime;
rb.velocity = new Vector2(inputX * walkSpeed, 0);
//rb.MovePosition(newPos);
}
}
private void SetFacingDirection(bool facingRight)
{
isFacingRight = facingRight;
//flip character
transform.localScale = isFacingRight? Vector3.one : new Vector3(-1, 1, 1);
lastFacingRight = isFacingRight;
}
public void MoveLeft()
{
inputX = -1f;
}
public void MoveRight()
{
inputX = 1f;
}
public void StopMove()
{
inputX = 0f;
}
}
}