赞
踩
演示
提示:以下是本篇文章正文内容,下面案例可供参考
示例:准备Player,Plane,Obstacle
代码如下(示例):
/**************************************************** 文件: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 Input Vector3 moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")); Vector3 moveVelocity = moveInput.normalized * moveSpeed; playerController.Move(moveVelocity); //Look Input Ray 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); } } } }
代码如下(示例):
/**************************************************** 文件: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); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。