Sh里,加Box collider 2D,Width:45 Height:45 Size X: 28 Y:28,选中Is Trigger,,加Rigidbody 2D,且不启用重力。
Food里,加Box collider 2D,Width:40 Height:40 Size X: 28 Y:28,选中Tags,输入food标签
{
public float velocity=0.35f;
public int step;
private int x;
private int y;
private Vector3 headPos;
void Start()
{
InvokeRepeating("Move",0,velocity);
x=0;y=step;
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
CancelInvoke();
InvokeRepeating("Move",0,velocity-0.2f);
}
if(Input.GetKeyUp(KeyCode.Space))
{
CancelInvoke();
InvokeRepeating("Move",0,velocity);
}
if(Input.GetKey(KeyCode.W)&&y!=-step)
{ gameObject.transform.localRotation=Quaternion.Euler(0,0,0);
x=0;y=step;
}
if(Input.GetKey(KeyCode.S)&&y!=step)
{
gameObject.tranform.localRotation=Quaternion.Euler(0,0,180);
x=0;y=-step;
}
if(Input.GetKey(KeyCode.A)&&x!=step)
{
gameObject.tranform.localRotation=Quaternion.Euler(0,0,90);
x=-step;y=0;
}
if(Input.GetKey(KeyCode.D)&&x!=-step)
{
gameObject.tranform.localRotation=Quaternion.Euler(0,0,-90);
x=step;y=0;
}
void Move()
{
headPos=gameObject.transform.localPosition;
gameObject.transform.localPosition=new Vector3(headPos.x+x,headPos.y+y)
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.CompareTag("Food"))
{
Destroy(collision.gameObject);
FoodMaker.Instance.MakeFood();
}
}