写一段unity3D人物移动代码
时间: 2023-02-22 16:49:09 浏览: 147
unity3d角色移动
好的,这是一段简单的 Unity3D 人物移动代码:
```
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
Vector3 movement;
Rigidbody playerRigidbody;
int floorMask;
float camRayLength = 100f;
void Awake ()
{
floorMask = LayerMask.GetMask ("Floor");
playerRigidbody = GetComponent <Rigidbody> ();
}
void FixedUpdate ()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Move (h, v);
Turning ();
}
void Move (float h, float v)
{
movement.Set (h, 0f, v);
movement = movement.normalized * speed * Time.deltaTime;
playerRigidbody.MovePosition (transform.position + movement);
}
void Turning ()
{
Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit floorHit;
if(Physics.Raycast (camRay, out floorHit, camRayLength, floorMask))
{
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
playerRigidbody.MoveRotation (newRotation);
}
}
}
```
该代码实现了人物在游戏中的基本移动,包括平面移动和转向。您可以根据需要进行修改和扩展。
阅读全文