20180427 筆記

最近在看 Unity 的 Tutorial… 官方的 Space Shooter 的影片似乎是舊版的 Unity ,所以有些寫法有變。

把練習的 code 貼一下免得忘記。在 PlayerController 這裡遇到的版本差異。

Space Shooter 這個 Tutorial Project 裡的 rigidbody 要用 GetComponent 去取用。

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerController : MonoBehaviour
{
public Rigidbody rigidbody;
public float speed;
public float tilt;
public Boundary boundary;
void Start ()
{
rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rigidbody.velocity = movement * speed;
rigidbody.position = new Vector3
(
Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax)
);
rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);
}
}

雷射子彈的 code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mover : MonoBehaviour
{
public Rigidbody rigidbody;
public float speed;
void Start()
{
rigidbody = GetComponent<Rigidbody>();
rigidbody.velocity = transform.forward * speed;
}
}