用unity脚本实现角色移动
时间: 2023-02-21 10:09:33 浏览: 133
在 Unity 中,角色移动可以通过使用脚本实现。下面是一个简单的代码示例,使用键盘控制角色移动:
```
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
Vector3 movement;
Animator anim;
Rigidbody playerRigidbody;
int floorMask;
float camRayLength = 100f;
void Awake ()
{
floorMask = LayerMask.GetMask ("Floor");
anim = GetComponent <Animator> ();
playerRigidbody = GetComponent <Rigidbody> ();
}
void FixedUpdate ()
{
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
Move (h, v);
Turning ();
Animating (h, v);
}
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);
}
}
void Animating (float h, float v)
{
bool walking = h != 0f || v != 0f;
anim.SetBool ("IsWalking", walking);
}
}
```
该代码使用 `Input.GetAxisRaw` 函数获取玩家输入的水平和垂直方向,然后使用 `Move` 函数对角色位置进行更新。其中 `Turning` 函数用于实现鼠标控制角色朝向,`Animating` 函数用于更新角色动画。
阅读全文