00|学到的内容
01|素材引入
02|地图配置
03|脚本编写
Man.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Man : MonoBehaviour
{
Vector2 man_direction;
// 自定义只在本脚本临时生效的名字,需要在编辑器选择具体生效层
public LayerMask Man_Layermask;
void Update()
{
if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow))
{
man_direction = Vector2.up;
}
if (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow))
{
man_direction = Vector2.down;
}
if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow))
{
man_direction = Vector2.left;
}
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow))
{
man_direction = Vector2.right;
}
if (man_direction != Vector2.zero && IsManMovable(man_direction))
{
MoveMan(man_direction);
}
man_direction = Vector2.zero;
}
public void MoveMan(Vector2 man_direction)
{
transform.Translate(man_direction);
}
// 如果碰到箱子,箱子能动人才能动
public bool IsManMovable(Vector2 man_direction)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, man_direction, 1f, Man_Layermask);
if (!hit)
{
return true;
}
else
{
// 需要确定到每一个实体
if (hit.collider.gameObject.GetComponent<Box>() != null)
{
// 箱子动了人才能动,是哪个箱子动在MoveBox选择
return hit.collider.GetComponent<Box>().MoveBox(man_direction);
}
}
return false;
}
}
Box.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Box : MonoBehaviour
{
public LayerMask Box_Layermask;
public bool MoveBox(Vector2 box_direction)
{
// 箱子是否撞墙,每个箱子都有这个脚本,transform就是相应箱子的
RaycastHit2D hit = Physics2D.Raycast(transform.position, box_direction, 1f, Box_Layermask);
if (!hit)
{
transform.Translate(box_direction);
return true;
}
else
{
return false;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("target"))
{
this.GetComponent<SpriteRenderer>().color = Color.black;
////this.gameObject.SetActive(false);
}
}
}