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

边栏推荐
猜你喜欢

【MySQL】使用MySQL Workbench软件新建表

What is an MQTT gateway?What is the difference with traditional DTU?

2022-08-01 Advanced Network Engineering (24) STP Advanced Knowledge

颜色选择器的使用

短视频同城流量宣传小魔推有何优势?如何给实体商家带来销量?

pytest之parametrize参数化

物联网时代下的网络整合推广外包精准化效果-深圳双赢世讯

解决win10win7win8系统找不到指定的模块,注册不了大漠插件的问题

【Rust指南】使用Cargo工具高效创建Rust项目 | 理解Rust特别的输入输出语句

Relaxation class: the boss will martial arts, who also can not hold up against!The charm of six sigma training
随机推荐
Rust learning: 6.2_ Tuples of composite types
941 · Sliding Puzzles
菜鸟、小白在autojs和冰狐智能辅助之间如何选择?
物联网时代下的网络整合推广外包精准化效果-深圳双赢世讯
ATH10 sensor reads temperature and humidity
IDLE开发wordCount程序(第五弹)
2022-08-01 网工进阶(二十三) VLAN高级技术-VLAN聚合、MUX VLAN
LaTeX出现错误代码Command \algorithmic already defined
Introduction to the delta method
【转】探秘钉钉的即时消息服务DTIM
Obtain - 65 [chances] : "soldiers, subtlety also - 7-36 meter reading - defeat
PLSQL学习第四天
pytest之parametrize参数化
iwemeta元宇宙:阿里首任COO:如何打造销售铁军
What is an MQTT gateway?What is the difference with traditional DTU?
CV+Deep Learning——网络架构Pytorch复现系列——classification(三:MobileNet,ShuffleNet)
uni 小程序腾讯地图polygon背景透明度
Summary of ctfshow SSTI knowledge points
每日一题,数组字符串的匹配问题
张驰课堂:老板会武术,谁也挡不住!六西格玛培训的魅力