赞
踩
1.创建角色和摄像机
在Unity中创建一个3D角色模型和一个摄像机,将角色模型拖拽到场景中,并将其设置为Player对象,将摄像机拖拽到场景中,并将其设置为Head对象。
2.设置摄像机参数
在Head对象上添加一个CinemachineFreeLooK脚本,用于实现自由视角,在CinemachineFreeLook脚本中,可以设置摄像机的旋转速度、 平滑度等参数。
3.编写控制角色移动的代码
在Player 对象上添加一个Rigidbody组件和一个CharacterController组件,在CharacterController组件中,可以设置角色的移动速度、跳跃高度等参数,然后,编写以下代码来控制角色的移动:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class jump : MonoBehaviour
- {
-
- // Start is called before the first frame update
- private Rigidbody rg;
- public bool isground = true;
- private AudioSource footvoice;
- void Start()
- {
- rg = GetComponent<Rigidbody>();
- footvoice = GetComponent<AudioSource>();
- }
-
- // Update is called once per frame
- void Update()
- {
- if (Input.GetKeyDown(KeyCode.Space) && isground)
- {
-
- rg.AddForce(Vector3.up * 200);
- }
- if ((Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D)) && isground)
- {
- if (footvoice.isPlaying == false)
- {
- footvoice.Play();
- }
- }
- else
- {
- footvoice.Stop();
- }
- }
- private void OnCollisionEnter(Collision collision)
- {
- if (collision.collider.tag == "ground")
- {
-
- isground = true;
- }
- }
- private void OnCollisionExit(Collision collision)
- {
- if (collision.collider.tag == "ground")
- {
-
- isground = false;
- }
- }
- }
4.编写控制视角的代码
在Head对象上添加一个 CinemachineFreeLook脚本,并设置好摄像机的旋转速度、平滑度等参数,然后,编写以下代码来控制视角:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class Move : MonoBehaviour
- {
- private Transform head;
- private Transform body;
- // Start is called before the first frame update
- void Start()
- {
- head = transform;
- body = transform.parent;
- Cursor.lockState = CursorLockMode.Locked;
- }
-
- // Update is called once per frame
- void Update()
- {
- float mousex = Input.GetAxis("Mouse X");
-
- if (mousex != 0)
- {
- body.Rotate(Vector3.up, mousex * 150 * Time.deltaTime);
- }
- float mousey = Input.GetAxis("Mouse Y");
- if (mousey != 0)
- {
- head.Rotate(Vector3.left, mousey * 150 * Time.deltaTime);
- }
- if (Vector3.Angle(body.forward, head.forward) > 60)
- {
- head.Rotate(Vector3.left, mousey * -100 * Time.deltaTime);
- }
-
- if (Input.GetKey(KeyCode.W))
- {
-
- body.Translate(Vector3.forward * 5.0f * Time.deltaTime);
- }
- if (Input.GetKey(KeyCode.S))
- {
-
- body.Translate(Vector3.back * 5.0f * Time.deltaTime);
- }
- if (Input.GetKey(KeyCode.A))
- {
-
- body.Translate(Vector3.left * 5.0f * Time.deltaTime);
- }
- if (Input.GetKey(KeyCode.D))
- {
-
- body.Translate(Vector3.right * 5.0f * Time.deltaTime);
- }
- }
- }
5.测试游戏功能
运行游戏,按下鼠标左键时,摄像机会变为自由视角,可以通过鼠标左右移动和上下移动来控制视角,同时,按下W、A、S、D键时,角色会向前、向左、向后、向右移动。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。