using UnityEngine;
public class playercontroller : MonoBehaviour
{
public float speed;
public float jumpForce;
private float moveInput;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
private Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
moveInput = Input.GetAxis("Horizontal");
rb.linearVelocity = new Vector2(moveInput * speed, rb.linearVelocity.y);
if(facingRight == false && moveInput > 0)
{
Flip();
}
else if(facingRight == true && moveInput< 0)
{
Flip();
}
if(moveInput == 0)
{
anim.SetBool("isRunning", false);
}
else
{
anim.SetBool("isRunning", true);
}
}
private void Update()
{
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
if(isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
rb.linearVelocity = Vector2.up * jumpForce;
anim.SetTrigger("takeOf");
}
if(isGrounded == true)
{
anim.SetBool("isJumping", true);
}
else
{
anim.SetBool("isJumping", false);
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
if (moveInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
}
else if (moveInput > 0)
{
transform.eulerAngles = new Vector3(0, 0, 0);
}
}
}
private void Start()
{
anim = GetComponent();
rb = GetComponent();
}
anim = GetComponent<Animator>();
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody2D _rb2d;
[Header("MovemengSetting")]
[SerializeField] private float _speed=4f;
[SerializeField] private float _jumpPower = 3f;
private float _inputX;
private bool _isGrounded;
[Header("GroundSetting")]
[SerializeField] Transform _feetPos;
[SerializeField] float _checkRad;
[SerializeField] LayerMask _groundMask;
private Animator _animator;
private SpriteRenderer _spRend;
private void Start()
{
_rb2d = GetComponent<Rigidbody2D>();
_animator = GetComponent<Animator>();
_spRend = GetComponent<SpriteRenderer>();
}
private void Update()
{
InputRead();
PlayerFlip();
AnimatorUpdate();
}
private void AnimatorUpdate()
{
_animator.SetBool("isRunning",_inputX!=0);
_animator.SetBool("isJumping", _isGrounded);
}
private void InputRead()
{
_inputX = Input.GetAxis("Horizontal");
if (Input.GetKeyDown(KeyCode.Space)) TryJump();
}
private void TryJump()
{
if (_isGrounded) _rb2d.linearVelocityY=_jumpPower;
}
void PlayerFlip()
{
_spRend.flipX = _inputX < 0;
}
private void FixedUpdate()
{
_isGrounded=IsGround();
Movement();
}
bool IsGround() => Physics2D.OverlapCircle(_feetPos.position, _checkRad, _groundMask);
void Movement()
{
_rb2d.linearVelocityX = _inputX * _speed;
}
#if UNITY_EDITOR
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawSphere(_feetPos.position, _checkRad);
}
#endif
}