1 void Update () { 2 float h = Input.GetAxis("Horizontal"); 3 float v = Input.GetAxis("Vertical"); 4 Vector3 vel = rigidbody.velocity; 5 if (Mathf.Abs(h) > 0.05f || Mathf.Abs(v) > 0.05f) { 6 rigidbody.velocity = new Vector3(-h * velocity, vel.y, -v * velocity); 7 transform.rotation = Quaternion.LookRotation(new Vector3(-h, 0, -v)); 8 } else { 9 if (agent.enabled == false) { 10 rigidbody.velocity = Vector3.zero; 11 } 12 } 13 if (agent.enabled) { 14 transform.rotation = Quaternion.LookRotation ( agent.velocity ); 15 } 16 }
1 using UnityEngine; 2 using System.Collections; 3 4 public class FollowTarget : MonoBehaviour { 5 6 public Vector3 offset; 7 private Transform player; 8 9 // Use this for initialization 10 void Start () { 11 player = GameObject.FindGameObjectWithTag("Player").transform; 12 } 13 14 // Update is called once per frame 15 void FixedUpdate () { 16 Vector3 targetPosition = player.position + offset; 17 transform.position = Vector3.Lerp(transform.position,targetPosition,Time.deltaTime*8.0f); 18 } 19 }
本文介绍了在Unity中实现角色移动的代码逻辑,通过输入轴控制速度和方向,并使用Quaternion.LookRotation进行方向调整。此外,还展示了如何创建一个跟随目标的脚本,使物体能够平滑地跟随玩家移动,适用于游戏开发中的各种场景。
9640

被折叠的 条评论
为什么被折叠?



