今天实现一个推箱子游戏的移动功能,以下是人物和箱子的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
Vector2 moveDir;
public LayerMask detectlayer;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.RightArrow))
moveDir = Vector2.right;
if (Input.GetKeyDown(KeyCode.LeftArrow))
moveDir = Vector2.left;
if (Input.GetKeyDown(KeyCode.UpArrow))
moveDir = Vector2.up;
if (Input.GetKeyDown(KeyCode.DownArrow))
moveDir = Vector2.down;
if (moveDir != Vector2.zero)
{
if (CanMoveToDir(moveDir))
{
Move(moveDir);
}
}
moveDir = Vector2.zero;
}
bool CanMoveToDir(Vector2 dir)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, dir, 1f, detectlayer);
if (!hit)
return true;
else
{
if (hit.collider.GetComponent() != null)
return hit.collider.GetComponent().CanMoveToDir(dir);
}
return false;
}
void Move(Vector2 dir)
{
transform.Translate(dir);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class box : MonoBehaviour
{
public bool CanMoveToDir(Vector2 dir)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position + (Vector3)dir * 0.5f, dir, 0.5f);
if (!hit)
{
transform.Translate(dir);
return true;
}
return false;
}
}