unity 2d怪物随机移动(隔一段时间随机切换移动向量)

基于2020.3版本,目前不会碰到物体自动移动,但是会根据时间切换移动方向

1.boss是空节点,巴鲁是怪物的显示图片

 

2.boss节点,需要有2d刚体组件,碰撞器和下方的脚本

3.巴鲁节点,需要挂载动画控制器,动画控制器总共有三个动画,分别是站立动画,移动动画和战斗动画,目前战斗不考虑

4.动画控制器的设置如下,切换参数是浮点数:speed

 5, 静止变成移动,当speed大于0.1的时候切换到移动,取消退出时间,取消过度,一般这两项我都会取消,因为有时候会感觉切换有卡顿。

 

6.随机移动脚本:

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

public class boss : MonoBehaviour
{
    public float speed = 10f; //移动速度
    Animator animator;
    Rigidbody2D rigBody;
    public Vector2 movePlay; //移动向量
    public float moveTimer; //移动计时器
    public float moveTime=3; // 移动时间

    void Start()
    {
        rigBody = GetComponent<Rigidbody2D>();
        //此处因为我的boss动画是空节点的子节点,而这个脚本是挂载在这个空节点上,因而需要获取到这个子节点
        animator = this.transform.Find("巴鲁").GetComponent<Animator>();
        //使用切换方向向量的函数
        moveAuto();
    }

    // Update is called once per frame
    void Update()
    {
        //判断计时器完毕没有
        if (moveTimer >= 0)
        {
            Vector3 thisScale = this.transform.localScale;
            Vector2 position = rigBody.position;
            position += movePlay * speed * Time.deltaTime;
            rigBody.MovePosition(position); //调用刚体的位置赋值的方法
            moveTimer -= Time.deltaTime;
        }
        else
        {
            //完毕了就重新调用,重新获取方向
            moveAuto();
            //计时器重新赋值
            moveTimer = moveTime;
        }
       
    }


    void moveAuto()
    {
        //随机生成-1,0,1的数字,因为随机数的Next不取最大值,此处用(-1,2)
        //此处随机生成移动向量
        System.Random rd = new System.Random();
        float x = rd.Next(-1, 2);
        float y = rd.Next(-1, 2);
        Debug.Log("x" + x + "y" + y);
        movePlay = new Vector2(x, y);
        //切换方向,
        //2d照片让scale的x取反就可以颠倒,而x的向量会取0,1,-1,不会是小数,scale默认是1,刚好第一张照片或者动画刚好是朝右方向的,只需要让原本的scale乘以x的向量(排除x=0)
        Vector3 thisScale = this.transform.localScale;
        if (x != 0)
        {
            thisScale.x = Math.Abs(thisScale.x) * x;
            transform.localScale = thisScale;
        }
        //判断移动静止
        //movePlay.magnitude这个属性可以判断当前的移动距离,具体没有看,后期补上去,与上面的speed不一样
        
        animator.SetFloat("speed", movePlay.magnitude);
    }
}

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值