写一段Unity 类似马里奥的2d移动跳跃代码
时间: 2024-05-13 09:16:09 浏览: 160
代码 unity3d 完整项目源码 2D Endless Jumper Toolkit unity3d asset
以下是一个简单的Unity类似马里奥的2D移动跳跃代码示例:
```csharp
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f; // 玩家移动速度
public float jumpForce = 10.0f; // 玩家跳跃力度
public LayerMask groundLayer; // 用于检测地面的层级
private Rigidbody2D rb;
private Animator animator;
private bool isGrounded = false;
private float horizontalInput = 0.0f;
private bool isJumping = false;
void Start()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
void Update()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump") && isGrounded)
{
isJumping = true;
}
}
void FixedUpdate()
{
// 水平移动
rb.velocity = new Vector2(horizontalInput * speed, rb.velocity.y);
// 检测是否在地面上
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 0.1f, groundLayer);
if (hit.collider != null)
{
isGrounded = true;
}
else
{
isGrounded = false;
}
// 跳跃
if (isJumping)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
isJumping = false;
}
// 动画控制
animator.SetFloat("Speed", Mathf.Abs(rb.velocity.x));
animator.SetBool("IsGrounded", isGrounded);
}
}
```
这个代码实现了玩家的左右移动、跳跃、动画控制以及检测是否在地面上。你可以将它附加到玩家对象上并进行测试。
阅读全文