Unity笔记 Project01 Basic
coconutnut

https://www.youtube.com/watch?v=pwZpJzpE2lQ&t=4178s&ab_channel=Imphenzia

实现

  1. 人物跳跃,左右移动

    • 跳跃速度与重量无关 -> ForceMode.VelocityChange

    • 跳跃时保持左右速度 -> rigidbodyComponent.velocity

    • 不可在空中跳跃 -> 检查Physics.OverlapSphere()

    • 左右移动同时检查←→AD -> Input.GetAxis(“Horizontal”)

    • 碰到墙壁不会因为长按D贴在墙上 -> 添加物理材质,摩擦力为0

  2. 摄像头跟随角色 -> 层级放在角色下即可

  3. 收集硬币

    • 不发生碰撞 -> 勾选是触发器
    • 检测碰撞 -> OnTriggerEnter()
    • 碰到后消除 -> Destroy(other.gameObject);

注意

  1. 在Update()中获取输入,在FixedUpdate()中apply physics
  2. 用[SerializeField] private,不要用public
  3. 减少不必要的Collider,提高效率
  4. 多用Prefab,善用Layer

代码

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

public class Player : MonoBehaviour
{
[SerializeField] private Transform groundCheckTransform = null;
[SerializeField] private LayerMask playerMask;
private bool jumpKeyPressed;
private float horizontalInput;
private Rigidbody rigidbodyComponent;

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

// Update is called once per frame
void Update() {
horizontalInput = Input.GetAxis("Horizontal");

// Avoid jumping in the air (always colliding with the capsule collider)
if(Physics.OverlapSphere(groundCheckTransform.position, 0.1f, playerMask).Length == 0){
return;
}

if(Input.GetKeyDown(KeyCode.Space)){
jumpKeyPressed = true;
}
}

// FixedUpdate is called once every physic update (Default 100/s)
private void FixedUpdate() {
if(jumpKeyPressed){
rigidbodyComponent.AddForce(Vector3.up * 5,ForceMode.VelocityChange);
jumpKeyPressed = false;
}

rigidbodyComponent.velocity = new Vector3(horizontalInput * 2, rigidbodyComponent.velocity.y, 0);
}

private void OnTriggerEnter(Collider other) {
// Collide with 9.Coin layer
if(other.gameObject.layer == 9){
Destroy(other.gameObject);
}
}

}