Unity 2D横版モバイルジャンプ

シーンを構築する

 緑の長方形がサーフェス、赤丸がプレイヤー

表面実装衝突コンポーネント

 プレイヤーはスチール製のボディコンポーネントと衝突コンポーネントを取り付けます

 衝突検出を連続に設定し、拘束をフリーズ回転 Z にチェックします。

プレーヤー上で MoveandJump という C# スクリプトを作成します。

コード

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveandJump : MonoBehaviour
{
    private Rigidbody2D rb;
    private Collider2D coli;

    public float speed, jumpForce;//移动速度,跳跃高度
    public Transform groundCheck;//地面检测,判断Player是否落地
    public LayerMask ground;//与那一次层级进行检测

    public bool isGround;//是否在地面的状态,true则在地面,false这在空中

    bool jumpPreesed;//将Update中的玩家输入和在FixedUpdate的跳跃方法连接起来
    int jumpCount;//跳跃次数

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        coli = GetComponent<Collider2D>();
    }

    void Update()
    {
        if (Input.GetButtonDown("Jump") && jumpCount > 0)
        {
            jumpPreesed = true;
        }
    }

    void FixedUpdate()
    {    
        //以groundCheck的位置为圆心,半径为0.1的圆进行检测,判断ground Layer是否在圆内
        isGround = Physics2D.OverlapCircle(groundCheck.position, 0.1f, ground);
        GroundMovement();
        Jump();
    }
    
    //移动
    void GroundMovement()
    {
        float horizontalMove = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(horizontalMove * speed, rb.velocity.y);
    }

    //跳跃
    void Jump()
    {
        //落回地面恢复跳跃次数
        if (isGround)
        {
            jumpCount = 2;
        }
        //第一次跳跃
        if (jumpPreesed && isGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
            jumpCount--;//跳跃次数-1
            jumpPreesed = false;//跳跃代码已执行完毕
        }
        //连跳
        else if (jumpPreesed && jumpCount >0 && !isGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
            jumpCount--;
            jumpPreesed = false;
        }
    }
}

おすすめ

転載: blog.csdn.net/qq_53401568/article/details/127681488
おすすめ