aiaiask.com©

开花即结果 提问即答案

Unity实现小球速度控制:W键加速S键减速,超80提示减速,归零提示加速,速度不小于零
原始问题:

Unity实现小球速度控制:W键加速S键减速,超80提示减速,归零提示加速,速度不小于零

要实现这个功能,首先需要创建一个Unity项目,并在场景中添加一个球体。然后,创建一个新的C#脚本,命名为"BallController",并将其附加到球体上。接下来,编写以下代码:

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

public class BallController : MonoBehaviour
{
    public float speed = 10f;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        if (movement != Vector3.zero)
        {
            transform.rotation = Quaternion.LookRotation(movement);
            rb.AddForce(transform.forward * speed);
        }

        if (speed > 80)
        {
            Debug.Log("减速");
        }
        else if (speed <= 0)
        {
            Debug.Log("加速");
        }
    }
}

这段代码首先获取球体的刚体组件,然后在Update方法中检测W和S键的输入。当按下W键时,速度增加;当按下S键时,速度减小。同时,根据速度的变化提示用户减速或加速。注意,这里的速度不能小于零。

Unity实现小球速度控制:W键加速S键减速,超80提示减速,归零提示加速,速度不小于零
AI / 模型iFLYTEK
时间 / DATEJune 16, 2024, 5:28 PM
语言zh-CN
IP / 区域江西 南昌