unity 教程1

1 添加 plane 与 Cube

Hierarchy窗口中右键 3D Object > Cube / Plane

并吧Cube命名为Player

Inspector窗口中设置Plane的Transform属性为如下

为Player对象添加 一个 Rigidbody 组件

此时运行这个项目,Player获得了物理属性。

2 为Player编写移动脚本

先为 Player 添加一个 New Script ,命名为Control

写入如下脚本

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

public class control : MonoBehaviour
{

public Rigidbody rb;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
if (Input.GetKey("d"))
{
rb.AddForce(50 * Time.deltaTime, 0, 0,ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
rb.AddForce(-50 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("w"))
{
rb.AddForce( 0, 0,50 * Time.deltaTime, ForceMode.VelocityChange);
}
}
}

运行项目,Player能够用方向键控制。

3 摄像机绑定

Main Camera添加脚本,命名为 Follow Player

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

using UnityEngine;

public class FollowPlayer : MonoBehaviour
{

public Transform player;
public Vector3 offset;

// Update is called once per frame
void Update()
{
transform.position = player.position + offset;
}
}

4 添加障碍和碰撞检测

新建一个Cube对象 命名为Obstacle

Player新添加一个脚本 Player Collision

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCollision : MonoBehaviour
{
public PlayerMovement movement;

private void OnCollisionEnter(Collision collision)
{
if(collision.collider.tag == "Obstacle")
{
movement.enabled = false;

}
}
}