using System.Collections.Generic;
using UnityEngine;
public class CatScript : MonoBehaviour
{
private Rigidbody2D body;
private float moveSpeed = 2.0f;
private bool _isGrounded;
public float JumpForce = 2.5f;
private bool facingRight = true;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody2D>();
body.freezeRotation = true;
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxisRaw("Horizontal");
body.velocity = new Vector2(h * moveSpeed, 0);
if (Input.GetKey(KeyCode.Space) && _isGrounded)
{
Debug.Log("jump");
body.velocity = new Vector2(body.velocity.x,JumpForce);
_isGrounded = false;
}
if (h < 0 && facingRight)
{
flip();
}
if (h > 0 && !facingRight)
{
flip();
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("GROUNDED");
if (collision.gameObject.tag == "Ground")
{
_isGrounded = true;
}
}
private void flip()
{
facingRight = !facingRight;
transform.Rotate(0, 180, 0);
}
}
using System.Collections.Generic;
using UnityEngine;
public class CatScript : MonoBehaviour
{
private Rigidbody2D body;
private float moveSpeed = 2.0f;
private bool _isGrounded;
public float JumpForce = 2.5f;
private bool facingRight = true;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody2D>();
body.freezeRotation = true;
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxisRaw("Horizontal");
body.velocity = new Vector2(h * moveSpeed, body.velocity.y); // Preserve the current y velocity.
if (Input.GetKeyDown(KeyCode.Space) && _isGrounded)
{
Debug.Log("Jump");
body.AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse);
_isGrounded = false;
}
if (h < 0 && facingRight)
{
flip();
}
if (h > 0 && !facingRight)
{
flip();
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("GROUNDED");
if (collision.gameObject.tag == "Ground")
{
_isGrounded = true;
}
}
private void flip()
{
facingRight = !facingRight;
transform.Rotate(0, 180, 0);
}
}
try it