鼠标控制人物旋转方向
- 前言
- 一、准备一些Object
- 二、代码示例
- 1.Player脚本
- 2.PlayerController脚本
- 3.Hierarchy面板
- 总结
前言
演示
提示:以下是本篇文章正文内容,下面案例可供参考
一、准备一些Object
示例:准备Player,Plane,Obstacle
二、代码示例
1.Player脚本
代码如下(示例):
/****************************************************文件:Player.cs作者:HKZ邮箱: 3046916186@qq.com日期:2022/1/9 12:2:45功能:Player输入(把此脚本挂在Player物体上)
*****************************************************/using UnityEngine;namespace HKZ
{[RequireComponent(typeof(PlayerController))]public class Player : MonoBehaviour{[SerializeField]private float moveSpeed = 5.0f;private Camera viewCamera;private PlayerController playerController;private void Start(){playerController = GetComponent<PlayerController>();viewCamera = Camera.main;}private void Update(){//Movement InputVector3 moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));Vector3 moveVelocity = moveInput.normalized * moveSpeed;playerController.Move(moveVelocity);//Look InputRay ray = viewCamera.ScreenPointToRay(Input.mousePosition);Plane groundPlane = new Plane(Vector3.up, Vector3.zero);float rayDistance;if (groundPlane.Raycast(ray, out rayDistance)){Vector3 point = ray.GetPoint(rayDistance);//Debug.DrawLine(ray.origin, point, Color.red);playerController.LockAt(point);}}}
}
2.PlayerController脚本
代码如下(示例):
/****************************************************文件:PlayerController.cs作者:HKZ邮箱: 3046916186@qq.com日期:2022/1/9 12:2:59功能:PlayerController方法
*****************************************************/using UnityEngine;namespace HKZ
{[RequireComponent(typeof(Rigidbody))]public class PlayerController : MonoBehaviour{private Vector3 velocity;private new Rigidbody rigidbody;private void Start(){rigidbody = GetComponent<Rigidbody>();}private void FixedUpdate(){rigidbody.MovePosition(rigidbody.position + velocity * Time.fixedDeltaTime);}public void Move(Vector3 moveVelocity){velocity = moveVelocity;}public void LockAt(Vector3 point){Vector3 heightCorrectedPoint = new Vector3(point.x, transform.position.y, point.z);transform.LookAt(heightCorrectedPoint);}}
}