编程语言
首页 > 编程语言> > Ruby‘s Adventrue游戏制作笔记(九)Unity添加敌人

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

作者:互联网

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);
        }
    }
}


转化为预制体

系列链接

还未编辑,发完后发链接。

标签:敌人,moveDirection,private,Unity,changeTimer,position,Ruby,Adventrue
来源: https://blog.csdn.net/Lmz_0314/article/details/121864745