在上一篇博文中,我主要记录了Unity中物体创建的方法。本篇文章我将梳理一下这个demo的运动逻辑。
MovingObject()类
首先创建一个MovingObject类,接下来Player和enemy的移动都将继承这类。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class MovingObject : MonoBehaviour {
public float moveTime = .1f;
public LayerMask blockingLayer; //碰撞层,所有的碰撞在这里发生
private BoxCollider2D boxCollider;
private Rigidbody2D rb2D;
private float inverseMoveTime;
protected virtual void Start()
{
boxCollider = GetComponent<BoxCollider2D>();
rb2D = GetComponent<Rigidbody2D>();
inverseMoveTime = 1f / moveTime;//速度
}
protected bool Move(int xDir,int yDir,out RaycastHit2D hit)//out为输出型参数,返回一个hit的物体
{
Vector2 start = transform.position;//先获得组件的位置
Vector2 end = start + new Vector2(xDir, yDir);
boxCollider