编译环境:Unity2020
作者:代码骑士
最后修改时间:2022/2/26
一、游戏程序演示
二、游戏玩法
按下ad键控制角色移动,躲避障碍物攻击同时避免角色掉落平台,坚持时间长者获胜。
三、制作步骤
1、准备素材
unity素材商店下载资源pixel Ad - Asset Store (unity.com)https://assetstore.unity.com/?q=pixel%20Ad&orderBy=1 搜索:Pixel Adventrue
选择这个素材并下载。
点击在unity中打开将素材包内容全部导入。
2、开始制作:
(1)游戏背景
Hierarchy右键选择3Dobject选择Quad,重命名background,调整quad和相机大小到合适尺寸。
Assets文件夹右键创建Material,命名BackGround,
点击下拉菜单,选择Unlit选择Textture ,
点击select添加图片
将做好的材质挂给BackGround
目前视角
创建脚本 backgroundMovement
using UnityEngine;
public class backgroundMovement : MonoBehaviour
{
Material material;//定义材质变量
Vector2 movement;//定义二维向量
public Vector2 speed;//二维向量的速度
void Start()
{
material = GetComponent<Renderer>().material;//获取渲染组件里面的材质模块
}
void Update()
{
movement -= speed * Time.deltaTime;//设置每帧移动速度
if(movement.y<-1.5)
{
movement.x = 0;movement.y = 0.85f;//循环
}
material.mainTextureOffset = movement;//位移差值等于速度
}
}
因为材质只有X和Y,所以用Vector2控制位置。
在X与Y方向增加速度即可。
点击播放,画面就开始移动了。
(2)设置最上方的陷阱
在资源文件夹里找Traps选择spikes。
调整像素大小为16点击应用。将其中一个图片拖入Hierarchy,position里面的Z调为-1(使他到背景前面)下一行的z调为180,使他翻转。
ctrl+D复制一排
创建空物体取名SpikeTop,将所有尖刺装进去
给整体加上物理组件
勾选is Trigger
(3)创建平台
选择一张素材拉进hierarchy,同时添加物理组件。
制作动画
设置平台消失标记
平台移动脚本 PlatFormMove
using UnityEngine;
public class PlatFormMove : MonoBehaviour
{
Vector3 movement;//transform是3D组件所以用Vector3
GameObject topline;//获取标志物
public float speed;//定义平台上升速度
void Start()
{
movement.y = speed;
topline = GameObject.Find("TopLine");
}
void Update()
{
MovePlantForm();
}
void MovePlantForm()
{
transform.position += movement * Time.deltaTime;//平台上升
if (transform.position.y >= topline.transform.position.y)//如果到达标记位就消失
Destroy(gameObject);
}
}
挂给创建的平台,使他向上移动
创建另一个物体:旋转平台
添加组件
Hinge joint 1=2D:以中心点旋转
同样的方式可以多加几个。
(4)添加角色
添加物理组件
判断角色是否接触到平台
创建子物体,编写代码PlayerController
using UnityEngine;
public class PlayerContrler : MonoBehaviour
{
Rigidbody2D rb;
float xVelocity;
public float speed;
public bool isOnGround;
public float checkRadius;
public LayerMask platform;
public GameObject groundCheck;
bool playerDead;
bool jump;
void Start()
{
rb = GetComponent<Rigidbody2D>();//获取物理组件
anim = GetComponent<Animator>();//获取动画组件
jump = true;
}
void Update()
{
isOnGround = Physics2D.OverlapCircle(groundCheck.transform.position, checkRadius, platform);
if (isOnGround) jump = true;
Movement();
}
void Movement()
{
xVelocity = Input.GetAxisRaw("Horizontal");
if (Input.GetKey("w")&&jump == true)
{
if(isOnGround)
{
rb.velocity = new Vector2(rb.velocity.x, 10f);
jump = false;
}
}
rb.velocity = new Vector2(xVelocity * speed, rb.velocity.y);
if (xVelocity != 0)
transform.localScale = new Vector3(xVelocity, 1, 1);
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(groundCheck.transform.position, checkRadius);
}
}