项目地址:https://github.com/giuyyt/unity_3d_character_project 3D游戏中控制角色的一些技巧。包括让角色移动,跳跃;以及镜头的跟随。 将一些技巧记录在此:
1.将镜头固定在角色上:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 using System.Collections;using System.Collections.Generic;using UnityEngine;public class CameraMove : MonoBehaviour { public Transform playerTransform; public float smoothing; private Vector3 offset; void Start ( ) { offset = transform.position - playerTransform.position; } void Update ( ) { Vector3 newCameraPos = playerTransform.position + offset; transform.position = Vector3.Lerp(transform.position, newCameraPos, smoothing * Time.deltaTime); } }
2.角色的移动:使用四个方向键:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 using System.Collections;using System.Collections.Generic;using UnityEngine;public class characterMove : MonoBehaviour { public float speed = 1.5f ; private Transform m_transform; void Start ( ) { m_transform = this .transform; } void Update ( ) { if (Input.GetKey(KeyCode.LeftArrow)) { m_transform.Translate(Vector3.left * Time.deltaTime * speed); } if (Input.GetKey(KeyCode.RightArrow)) { m_transform.Translate(Vector3.right * Time.deltaTime * speed); } if (Input.GetKey(KeyCode.UpArrow)) { m_transform.Translate(Vector3.forward * Time.deltaTime * speed); } if (Input.GetKey(KeyCode.DownArrow)) { m_transform.Translate(Vector3.back * Time.deltaTime * speed); } } }
3.角色跳跃:按空格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 using System.Collections;using System.Collections.Generic;using UnityEngine;public class characterJump : MonoBehaviour { public float force = 5f ; private Rigidbody myRigidbody; void Start ( ) { myRigidbody = gameObject.GetComponent<Rigidbody>(); } void Update ( ) { if (Input.GetKey(KeyCode.Space)) { if (IsGrounded(1f )) { myRigidbody.AddForce(new Vector3(0 , force, 0 ), ForceMode.Impulse); } } } public bool IsGrounded (float distance ) { bool b = Physics.Raycast(new Vector3(transform.position.x, transform.position.y, transform.position.z), -Vector3.up, distance); return b; } }
此处注意要把角色的RigidBody中Constraints中的三个Rotation给Freeze掉,否则角色跳跃可能会翻倒。