当前位置:网站首页>【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轴)

边栏推荐
- 短视频同城流量宣传小魔推有何优势?如何给实体商家带来销量?
- Big guy, when Oracle single-table incremental synchronization, the source database server takes up nearly 2g of memory. This is not normal, right?
- 数据库公共字段自动填充
- Add spark related dependencies and packaging plugins (sixth bullet)
- navicat for mysql 连接时报错:1251-Client does not support authentication protocol requested by server
- 关于数据库中的中文模糊检索探讨
- PHP笔记 28 29 30 31
- ATH10 sensor reads temperature and humidity
- Uni-app develops WeChat applet using local images as background images
- phpstudy starts automatically
猜你喜欢

Rust学习:6.3_复合类型之元组

如何设计神经网络结构,神经网络设计与实现

初使jest 单元测试

MySQL设置初始密码—注意版本mysql-8.0.30

js reduce

DGIOT 30 million meters set pressure reading

nrm 使用详解

iwemeta元宇宙:阿里首任COO:如何打造销售铁军

Solve the problem that the win10win7win8 system cannot find the specified module and cannot register the desert plug-in

基于STC8G2K64S4单片机通过OLED屏幕显示模拟量光敏模拟值
随机推荐
Using the color picker
什么是长轮询
LaTeX出现错误代码Command \algorithmic already defined
MySQL设置初始密码—注意版本mysql-8.0.30
二叉树 --- 堆
.NET-8. My Thought Notes
浅谈C语言实现冒泡排序
SCS【2】单细胞转录组 之 cellranger
明明加了唯一索引,为什么还是产生重复数据?
MySQL database monthly growth problem
DGIOT支持工业设备租赁以及远程管控
每日一题,数组字符串的匹配问题
DGIOT 30 million meters set pressure reading
【NeRF】原始论文解读
大佬,oracle单表增量同步时候源库服务器额外占用内存近2g,这不正常吧
VS2013-调试汇编代码-生成asm文件-结构体内存布局-函数参数压栈-调用约定
FFT模板
一文2600字手把手教你编写性能测试用例
英国国家卫生服务遭受攻击,系统出现大面积故障
进程管理(动态的)