Ruby‘s Adventrue游戏制作笔记(九)Unity添加敌人

  • Post author:
  • Post category:其他


Ruby’s Adventrue游戏制作笔记(九)Unity添加敌人




前言

本文章是我学习Unity官方项目项目所做笔记,作为学习Unity的游戏笔记,在最后一章会发出源码,如果等不及可以直接看源码,里面也有很多注释相关,话不多说,让Ruby动起来!

游戏引擎:Unity2020.3



一、编辑敌人

将敌人拖入编辑器中

添加刚体和碰撞器

设置重力影响为0

在这里插入图片描述

编辑碰撞器范围

在这里插入图片描述



二、编辑敌人脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// 敌人的脚本
public class EnemyController : MonoBehaviour
{
    // 移动速度
    public float speed = 5f;

    // 敌人伤害
    private int enemyDamage = -1;

    // 改变方向的时间
    public float changeDirectionTime = 2f;

    // 改变方向的计时器
    private float changeTimer;

    // 是否垂直方向移动
    public bool isVertical;

    // 移动方向
    private Vector2 moveDirection; 

    private Rigidbody2D rbody;



    // Start is called before the first frame update
    void Start()
    {
        // 获取刚体组件
        rbody = GetComponent<Rigidbody2D>();

        // 如果是垂直移动,朝上移动,如果不是,则方向朝右
        moveDirection = isVertical ? Vector2.up : Vector2.right;

        changeTimer = changeDirectionTime;
    }

    // Update is called once per frame
    void Update()
    {


        changeTimer -= Time.deltaTime;
        if(changeTimer < 0)
        {
            // 改变方向
            moveDirection *= -1;
            // 重新计时
            changeTimer = changeDirectionTime;
        }

        // 控制移动
        Vector2 position = rbody.position;
        position.x += moveDirection.x * speed * Time.deltaTime;
        position.y += moveDirection.y * speed * Time.deltaTime;
        rbody.MovePosition(position);
    }


    // 与玩家的碰撞检测
    // 刚体碰撞检测
    private void OnCollisionEnter2D(Collision2D collision)
    {
        PlayerController pc = collision.gameObject.GetComponent<PlayerController>();
        if (pc != null)
        {
            pc.ChangeHealth(enemyDamage);
        }
    }
}


转化为预制体



系列链接


Ruby‘s Adventrue游戏制作笔记(一)Unity创建项目


Ruby‘s Adventrue游戏制作笔记(二)Unity控制ruby移动


Ruby‘s Adventrue游戏制作笔记(三)Unity使用tilemap绘制场景


Ruby‘s Adventrue游戏制作笔记(四)Unity绘制其他元素


Ruby‘s Adventrue游戏制作笔记(五)Unity解决碰撞抖动和旋转问题


Ruby‘s Adventrue游戏制作笔记(六)Unity相机跟随玩家移动


Ruby‘s Adventrue游戏制作笔记(七)Unity采集生命道具


Ruby‘s Adventrue游戏制作笔记(八)Unity伤害陷阱


Ruby‘s Adventrue游戏制作笔记(九)Unity添加敌人


Ruby‘s Adventrue游戏制作笔记(十)Unity添加动画


Ruby‘s Adventrue游戏制作笔记(十一)Unity角色攻击——发射子弹


Ruby‘s Adventrue游戏制作笔记(十二)Unity给角色添加简单的特效


Ruby‘s Adventrue游戏制作笔记(十三)Unity血条UI的显示


Ruby‘s Adventrue游戏制作笔记(十四)Unity播放游戏音效


Ruby‘s Adventrue游戏制作笔记(十五)UnityNPC对话


Ruby‘s Adventrue游戏制作笔记(十六)Unity子弹数量及其UI


Ruby‘s Adventrue游戏制作笔记(十七)Unity添加游戏胜利条件和失败条件和导出游戏



版权声明:本文为Lmz_0314原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。