经典游戏案例:吃豆人
学习目标:游戏核心玩法实现
游戏画面
项目结构目录
部分核心代码
public class GhostMove : MonoBehaviour {
public AudioSource source;
public AudioClip sound;
public Transform[] waypoints;
int cur = 0;
public float speed = 0.3f;
void Start() {
source.clip = sound;
}
void FixedUpdate () {
// Waypoint not reached yet? then move closer
if (transform.position != waypoints[cur].position) {
Vector2 p = Vector2.MoveTowards(transform.position,
waypoints[cur].position,
speed);
GetComponent<Rigidbody2D>().MovePosition(p);
}
// Waypoint reached, select next one
else cur = (cur + 1) % waypoints.Length;
// Animation
Vector2 dir = waypoints[cur].position - transform.position;
GetComponent<Animator>().SetFloat("DirX", dir.x);
GetComponent<Animator>().SetFloat("DirY", dir.y);
}
void OnTriggerEnter2D(Collider2D co) {
if (co.name == "pacman") {
Destroy (co.gameObject);
Messenger.Broadcast (GameEvent.PACMAN_HIT);
source.Play();
}
}
}