So I’ve been trying to learn to use Unity and C#, but I can’t understand why this crashes. Can anyone find the glaringly obvious error and tell me what I’m doing wrong? I thought for sure this would work
public class Ghost : MonoBehaviour {
public GameObject ThePac;
public float ghostSpeed = 1.5f;
private int XorY = 1;
private int colCount = 0;
// Use this for initialization
void Start () {
MoveY();
}
// Update is called once per frame
void Update () {
}
void MoveY()
{
Vector2 newPosition = transform.position;
XorY = 1;
if (ThePac.transform.position.y > transform.position.y)
{
while (colCount == 0)
{
newPosition.y += (1 * ghostSpeed * Time.deltaTime);
transform.position = newPosition;
}
}
if (ThePac.transform.position.y < transform.position.y)
{
while (colCount == 0)
{
newPosition.y += (-1 * ghostSpeed * Time.deltaTime);
transform.position = newPosition;
}
}
}
void MoveX()
{
Vector2 newPosition = transform.position;
XorY = 0;
if (ThePac.transform.position.x > transform.position.x)
{
while (colCount == 0)
{
newPosition.x += (1 * ghostSpeed * Time.deltaTime);
transform.position = newPosition;
}
}
if (ThePac.transform.position.x < transform.position.x)
{
while (colCount == 0)
{
newPosition.x += (-1 * ghostSpeed * Time.deltaTime);
transform.position = newPosition;
}
}
}
void OnCollisionEnter2D (Collision2D col)
{
colCount = 0;
if (XorY == 1)
MoveX ();
if (XorY == 0)
MoveY ();
}
void OnCollisionExit2D (Collision2D col)
{
colCount = 1;
}
}
Hm, I’m not sure how to do this sort of behavior without looping though. Just to simplify things starting off, I was trying to make it to go along a y-axis path until it hits a wall, then go along a x-axis path until it hits a wall, etc.
Guess I’ll scrap this and try to think of something a little less infinite. Also, I have a feeling I should be using raycasts to change direction instead of waiting until I run into a wall.