PlayerMovement
unknown
csharp
2 years ago
2.5 kB
11
Indexable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
private float Move;
public float speed;
public float jump;
public Vector2 boxSize;
public float castDistance;
public LayerMask groundLayer;
public CoinManager cm;
private Animator anim;
private bool isFacingLeft;
public GameObject player;
public Transform spawnPoint;
bool grounded;
// Start is called before the first frame update
void Start()
{
player.transform.position = spawnPoint.position;
isFacingLeft = true;
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Move = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(Move * speed, rb.velocity.y);
if(Input.GetButtonDown("Jump") && isGrounded())
{
rb.AddForce(new Vector2(rb.velocity.x, jump * 10));
}
if(Move != 0)
{
anim.SetBool("isRunning", true);
}
else
{
anim.SetBool("isRunning", false);
}
anim.SetBool("isJumping", !isGrounded());
if(!isFacingLeft && Move < 0)
{
Flip();
}else if(isFacingLeft && Move > 0)
{
Flip();
}
if (isGrounded())
{
rb.gravityScale = 10;
}
else
{
rb.gravityScale = 1;
}
}
public void Flip()
{
isFacingLeft = !isFacingLeft;
Vector3 localScale = transform.localScale;
localScale.x *= -1f;
transform.localScale = localScale;
}
public bool isGrounded()
{
if(Physics2D.BoxCast(transform.position, boxSize, 0, -transform.up, castDistance, groundLayer))
{
return true;
}
else
{
return false;
}
}
private void OnDrawGizmos()
{
Gizmos.DrawWireCube(transform.position-transform.up * castDistance, boxSize);
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.CompareTag("Coin"))
{
Destroy(other.gameObject);
cm.coinCount++;
}
}
}
Editor is loading...
Leave a Comment