写一段unity3D物体移动的代码
时间: 2024-05-05 12:20:14 浏览: 24
以下是一个简单的Unity3D物体移动的代码示例:
```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectMovement : MonoBehaviour
{
public float speed = 10f; // 移动速度
void Update()
{
// 获取输入方向
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
// 计算移动方向
Vector3 direction = new Vector3(horizontal, 0f, vertical);
// 移动物体
transform.position += direction * speed * Time.deltaTime;
}
}
```
这个示例中,我们定义了一个`speed`变量,用于控制物体的移动速度。在`Update`函数中,我们通过`Input.GetAxis`获取玩家的输入方向,并计算出对应的移动方向向量。最后,我们将物体的位置加上移动方向向量的乘积和速度的乘积,以实现物体的移动。注意,我们要将速度乘上`Time.deltaTime`,这样可以确保移动速度不受帧率影响。