当前位置:网站首页>【Unity入门计划】2D游戏实现敌人来回移动控制脚本
【Unity入门计划】2D游戏实现敌人来回移动控制脚本
2022-08-10 07:59:00 【flashinggg】
目录
学习的教程
【unity2021入门教程】74-2D游戏开发教程系列-03-RubyAdventure2DRpg官方教程-22-移动敌人方式2_哔哩哔哩_bilibili
移动脚本
这里教程中列举出了两种控制移动的版本,我又自己写了一版可以实现简单的控制敌人移动方向、移动速度、以及沿着x轴或y轴移动的脚本,这里贴出来记录。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
Rigidbody2D robotrigidbody2D;
//移动速度
public int moveSpeed;
//移动最大距离
public float moveDistance;
//false为Y轴移动,true为水平移动
public bool X;
//移动方向,令初始移动方向为轴的正方向
int direction = 1;
//初始坐标值
float initx, inity;
//存放当前位置
Vector2 position;
//储存当前与起始点距离
float currentDis;
void Start()
{
robotrigidbody2D = GetComponent<Rigidbody2D>();
//移动起点
initx = transform.position.x;
inity = transform.position.y;
}
// Update is called once per frame
void Update()
{
}
//物理引擎相关的操作都要发放在这里
//默认0.02s执行一次
private void FixedUpdate()
{
//获取每帧当前的刚体位置
position = robotrigidbody2D.position;
if (X)//x轴移动
{
position.x += moveSpeed * direction * Time.deltaTime;
currentDis = Mathf.Abs(position.x - initx);
if (currentDis < 0.01f || currentDis > moveDistance)
{
direction *= -1;
}
}
else//y轴移动
{
position.y += moveSpeed * direction * Time.deltaTime;
currentDis = Mathf.Abs(position.y - inity);
if (currentDis < 0.01f || currentDis > moveDistance)
{
direction *= -1;
}
}
//更改位置
robotrigidbody2D.MovePosition(position);
//robotrigidbody2D.position = position;
}
}
脚本中,用了一个初始值为1的变量direction用来改变移动方向;如果判断需要改变移动方向了,则乘上1,即脚本中的
direction *= -1;
direction自始至终都是在-1和1之间来回切换值,也实现了移动方向的改变。
控制界面

效果
X√

X 未选(y轴)

边栏推荐
- Process management (dynamic)
- Rust learning: 6.4_ enumeration of composite types
- 上课笔记(7)(1)——#647. 找树根和孩子(root)
- Power function Exponential function Logarithmic function
- WooCommerce 安装和 rest api 使用
- Uni applet Tencent map polygon background transparency
- 探索神经网络架构教程视频,设计神经网络的步骤
- js函数聚合的三种实现方式
- WooCommerce installation and rest api usage
- 【MySQL】使用MySQL Workbench软件新建表
猜你喜欢
随机推荐
js reduce
【MySQL】SQL语句
90.(cesium之家)cesium高度监听事件
明明加了唯一索引,为什么还是产生重复数据?
WooCommerce installation and rest api usage
uni 小程序腾讯地图polygon背景透明度
.NET-8.我的思想笔记
Uni applet Tencent map polygon background transparency
2022-08-01 Advanced Network Engineering (23) Advanced VLAN Technology - VLAN Aggregation, MUX VLAN
Obtain - 65 [chances] : "soldiers, subtlety also - 7-36 meter reading - defeat
如何治理资源浪费?百度云原生成本优化最佳实践
DGIOT 30 million meters set pressure reading
Rust学习:6.4_复合类型之枚举
Summary of ctfshow SSTI knowledge points
自动化测试框架Pytest(二)——前后置处理
PLSQL学习第二天
【Rust指南】使用Cargo工具高效创建Rust项目 | 理解Rust特别的输入输出语句
关于数据中心的设计方案,数据中心网络规划设计
二叉树 --- 堆
What is an MQTT gateway?What is the difference with traditional DTU?









