Unity一些杂七杂八的笔记
coconutnut

简单Player移动

  1. 主摄像头放到Player下

  2. 加script

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class PlayerController : MonoBehaviour
    {
    CharacterController controller;
    public float speed = 5;

    void Start()
    {
    controller = GetComponent<CharacterController>();
    }

    void Update()
    {
    // movement
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 move = transform.right * x + transform.forward * z;
    controller.Move(move * speed * Time.deltaTime);
    }
    }

NPC漫游

  1. 导入城市资源

  2. 给所有物体加Mesh Collider(否则后面检测人行道时
    Physics.Raycast无法检测)

  3. 给人行道设置layer为sidewalk,导航->对象->Navigation Static

  4. 给桌椅、房子等设置Navigation Static,Not Walkable

  5. 放一个胶囊当NPC,加组件Nav Mesh Agent

  6. 加script(ref:FULL 3D ENEMY AI in 6 MINUTES! || Unity Tutorial

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
48
49
50
51
52
53
54
55
56
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class CitizenController : MonoBehaviour
{
public NavMeshAgent agent;

public LayerMask groudMask;

// patroling
Vector3 walkPoint;
bool walkPointSet;
public float walkPointRange = 20;

void Start()
{
agent = GetComponent<NavMeshAgent>();
}

void Update()
{
Patroling();
}

private void Patroling()
{
if (!walkPointSet) SearchWalkPoint();

if (walkPointSet)
agent.SetDestination(walkPoint);

Vector3 distanceToWalkPoint = transform.position - walkPoint;

// walkpoint reached
if (distanceToWalkPoint.magnitude < 1f)
walkPointSet = false;

// not moving
if(agent.speed < 1f)
walkPointSet = false;
}

private void SearchWalkPoint()
{
// calculate random point in range
float randomZ = Random.Range(-walkPointRange, walkPointRange);
float randomX = Random.Range(-walkPointRange, walkPointRange);

walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);

if (Physics.Raycast(walkPoint, -transform.up, 2f, groudMask))
walkPointSet = true;
}
}
  1. 设置script引用