unity人物移动脚本
时间: 2023-03-28 14:05:00 浏览: 150
unity角色移动
4星 · 用户满意度95%
你可以使用以下代码实现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, f, 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 = f;
Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
playerRigidbody.MoveRotation(newRotation);
}
}
void Animating(float h, float v)
{
bool walking = h != f || v != f;
anim.SetBool("IsWalking", walking);
}
}
```
阅读全文