【问题标题】:Jump when pressing a button (unity 2D)按下按钮时跳转(unity 2D)
【发布时间】:2020-06-17 01:53:57
【问题描述】:

我正在制作我的第一个手机游戏,但我不知道如何在按下按钮时让玩家跳跃。这是我的代码:

using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
public class Move2D : MonoBehaviour
{
    public float speed = 5f;
    public float jumpSpeed = 8f;
    private float movement = 0f;
    private Rigidbody2D rigidBody;

    // Use this for initialization
    void Start()
    {
        rigidBody = GetComponent<Rigidbody2D>();


    }

    // Update is called once per frame
    void Update()
    {
        movement = CrossPlatformInputManager.GetAxis("Horizontal");
        rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);

        if (CrossPlatformInputManager.GetButtonDown("Jump") && rigidBody.velocity.y == 0)

        {
            rigidBody.AddForce(transform.up * jumpSpeed, ForceMode2D.Impulse);
        }
    }
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    这很简单,这应该是最简单的方法。

    1) 在 Canvas UI 中创建一个按钮

    2) 在“Move2D”类中创建公共“Jump()”函数

    3) 为 Canvas UI 中的按钮事件分配此公共“Jump()”函数

    public class Move2D : MonoBehaviour
    {
        public void Jump()
        {
            rigidBody.AddForce(transform.up * jumpSpeed, ForceMode2D.Impulse);
        }
    }
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    相关资源
    最近更新 更多