要实现这个功能,首先需要创建一个Unity项目,并在场景中添加一个球体。然后,创建一个新的C#脚本,命名为"BallController",并将其附加到球体上。接下来,编写以下代码:
```csharp
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键时,速度减小。同时,根据速度的变化提示用户减速或加速。注意,这里的速度不能小于零。
```csharp
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键时,速度减小。同时,根据速度的变化提示用户减速或加速。注意,这里的速度不能小于零。