using UnityEngine;
using System.Collections;
public class PacmanMove : MonoBehaviour {
public float speed = 0.4f;///定义公共变量 速度
Vector2 dest = Vector2.zero;
void Start () {
dest = transform.position;
}
void FixedUpdate()
{
// Move closer to Destination
Vector2 p = Vector2.MoveTowards(transform.position, dest, speed);
GetComponent<Rigidbody2D>().MovePosition(p);
// Check for Input if not moving
if ((Vector2)transform.position == dest)
{
if (Input.GetKey(KeyCode.UpArrow) && valid(Vector2.up))
dest = (Vector2)transform.position + Vector2.up;
if (Input.GetKey(KeyCode.RightArrow) && valid(Vector2.right))
dest = (Vector2)transform.position + Vector2.right;
if (Input.GetKey(KeyCode.DownArrow) && valid(-Vector2.up))
dest = (Vector2)transform.position - Vector2.up;
if (Input.GetKey(KeyCode.LeftArrow) && valid(-Vector2.right))
dest = (Vector2)transform.position - Vector2.right;
}
// Animation Parameters
Vector2 dir = dest - (Vector2)transform.position;
GetComponent<Animator>().SetFloat("DirX", dir.x);
GetComponent<Animator>().SetFloat("DirY", dir.y);
}
bool valid(Vector2 dir) ////往前投线判断有没有墙
{
// Cast Line from 'next to Pac-Man' to 'Pac-Man'
Vector2 pos = transform.position; ///定义一个坐标pos
RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos); ///线 hit
return (hit.collider == GetComponent<Collider2D>());
}
}
using UnityEngine;
using System.Collections;
public class pacot : MonoBehaviour {
void OnTriggerEnter2D(Collider2D co)
{
if (co.name == "pacman")
Destroy(gameObject);
}
}
using UnityEngine;
using System.Collections;
public class GhostMove : MonoBehaviour {
public Transform[] waypoints;
int cur = 0;
public float speed = 0.3f;
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);
}
}