Unity笔记 Project04 点击移动+旋转摄像头
coconutnut

想做成点击移动,并且摄像头可以根据鼠标位置有限制的旋转

Step 1 - 点击移动

参照Project02

完成~

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class PlayerMovement : MonoBehaviour
{
public NavMeshAgent agent;

// Start is called before the first frame update
void Start()
{
agent = GetComponent<NavMeshAgent>();
}

// Update is called once per frame
void Update()
{
// Click to Move
if(Input.GetMouseButtonDown(0)){
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit, Mathf.Infinity)){
agent.SetDestination(hit.point);
}
}
}
}

Step 2 - 旋转摄像头

参照Project03

鼠标转向不是很方便,顺便加了方向键旋转

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public float keySensitivity = 100f;
public Transform player = null;
private float xRotation = 0f;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
// Get mouse position
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

// Get key inout
float keyX = Input.GetAxis("Horizontal") * keySensitivity * Time.deltaTime;

Debug.Log(mouseX);
Debug.Log(keyX);

// Rotate camera up and down
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -30f, 30f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

// Rotate player left and right
player.Rotate(Vector3.up * (mouseX + keyX));
}
}

耶(^-^)V

目前这个移动方式很满意,暂时就这样

下一步可以搭场景啦~