由roguelike《拾荒者》学习Unity(二)

本文是关于Unity游戏开发的学习笔记,主要讲解MovingObject类和Player类的运动逻辑。MovingObject类用于实现物体的移动,包括Start()、Move()和onCantMove()函数,而Player类继承MovingObject,处理键盘输入并调用 AttemptMove()。文章还分享了防止精灵重叠的小技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在上一篇博文中,我主要记录了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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值