当前位置:网站首页>Unity2D horizontal version game tutorial 4 - item collection and physical materials
Unity2D horizontal version game tutorial 4 - item collection and physical materials
2022-07-31 00:47:00 【Really fine duck】
Let's expand the background a bit first,ctrl+DDuplicate a background image and adjust the position,Expand the map a little bit

然后再HierarchyThe interface creates an empty component named Collection,表示物品,Create an empty child component called Cherries,This is the cherry item,Pickable,The property bar on the right givesCherries添加一个Sprite Renderer(精灵渲染器)

Next we will giveCherriesModel is set up,我们到Item文件夹,There are three different items here,The third folder is some fruit,We choose cherries,Don't forget to change the pixel of the cherry to 32

Then we drag the animation for the first frame toCherries的Sprite Renderer

Set the layer order,Set to what we have set beforeCollection图层,This way you can see the item in the scene

Then we add an animation effect to the item,Same as the previous character animation,这里就略过了,If you forget, you can read the previous article,After the animation is done,我们还需要给Cherries添加碰撞体,property bar thereCherries添加一个circle Collider 2D

调整一下位置,然后勾选Is Trigger,Think of this collider as a trigger

Then we're going to write a little bit of code
First create a variable that counts,Used to count the character's score or the number of items collected

There is also the variable that the character hits the item to destroy the item and counts it1
We treat this cherry as oneTrigger(触发器),所以我们用Triggertype to determine whether it is a collectible item,这里TriggerThe type of item is set by settingTag来区分

新建一个Tag,命名为Collection

Then we will cherryTag改成Collection,Behind the different types of collectible itemsTag都改成Collection

设置完TagThen we can write it in the code

这里输出cherries的值来debug,我们回到unity运行,It prints when we hit a cherrycherries的值是1

Don't forget to take usdebugComment out that line of code
We've only put a cherry on the map right now,If we want to put more cherries we have to put them one by one,And if you want to make changes to all the cherries, you need to set them one by one,Here we introduce prefabs(Perfabs)的概念,The role of prefabs is to reuse resources.Objects that are reused in the scene are made into prefabs as much as possible.
我们通过将HierarchyDrag the object in the opposite direction into the folder to make the object into a prefab,Then drag the prefab in the folder to the scene to become a prefab instance.We modify the prefab,All prefab instances are modified accordingly,We modify the prefab instance,Other examples of prefabs including prefabs do not change.
So once we have a prefab, we can keep duplicating it,Modify the prefab when you want to change it. All prefab instances are changed accordingly,If you want to have a deeper understanding of prefabs, you can refer to this article详解Unity中的预制体_Dream Xiaotianyou's blog-CSDN博客_unity预制体
然后我们创建一个文件夹,命名为Prefabs,然后将Hierarchy里面的cherries拖进Prefabs文件夹,这样就有了cherries预制体,这时候cherries会变成蓝色.

然后我们ctrl+D复制一下cherries,Add a little more cherry to the map

This completes the collection of items,Now let's modify the character to be stuck on other collidersbug.The character itself has a collider,tilemapThere is also a collider,So when the character touches other objects it will get stuck on the object,Because of friction,We add a smooth physical material to the character
我们在Assets文件夹右键->Create->2D->physics Material 2D,创建一个2D的物理材质

Then adjust both parameters of this material to 0,friction是摩擦力,bouncinessis the resilience

Then drag this material to the charactercircle collider 2D

This way our character doesn't rub against other colliders
Finally, paste the complete code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playercontroller : MonoBehaviour
{
private Rigidbody2D rb;//获得Rigidbody2D组件
private Collider2D coll;//获得Collider2D组件
private Animator anim;//获得动画组件
public float speed, jumpForce;//公开,设置速度和跳跃力
public LayerMask ground;//获得地面图层
public Transform groundCheck;//Detects if the character hits the ground
private bool isJump, isGround;//判断是否按下空格键,判断是否在地面
private int jumpCount;//Used to set the character is a few jumps
private int cherries;//计数变量
//初始化
void Start()
{
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<Collider2D>();
anim = GetComponent<Animator>();
}
void Update()
{
//如果按下空格键并且在地面上
if (Input.GetKeyDown(KeyCode.Space) && jumpCount > 0)
{
isJump = true;
}
}
private void FixedUpdate()
{
isGround = Physics2D.OverlapCircle(groundCheck.position, 0.1f, ground);
Movement();
Jump();
SwitchAnim();
}
//基础移动
void Movement()
{
float horizontal = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);//设置x轴的移动
//设置角色的转向问题
if (horizontal != 0)
{
transform.localScale = new Vector3(horizontal, 1, 1);
anim.SetBool("run", true);
}
else
anim.SetBool("run", false);
}
//跳跃
void Jump()
{
//If you set a double jump on the ground
if (isGround)
{
jumpCount = 2;
}
//Press the jump key and be on the ground
if (isJump && isGround)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpCount--;
isJump = false;
}
//Press the jump key without being on the ground andjumpCount大于0
else if (isJump && !isGround && jumpCount > 0)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpCount--;
isJump = false;
}
}
//切换动画
void SwitchAnim()
{
//if in a falling state
if (rb.velocity.y < 0 && !isGround)
{
anim.SetBool("fall", true);
anim.SetBool("jump", false);
}
//如果在跳跃状态
if (!isGround && rb.velocity.y > 0)
{
anim.SetBool("jump", true);
}
//如果在地面上
else if (coll.IsTouchingLayers(ground))
{
anim.SetBool("fall", false);
}
}
//Determine if the object is touched
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag=="Collection")
{
Destroy(collision.gameObject);
cherries++;
//Debug.Log(cherries);
}
}
}边栏推荐
- Thesis understanding: "Designing and training of a dual CNN for image denoising"
- SereTOD2022 Track2代码剖析-面向半监督和强化学习的任务型对话系统挑战赛
- ES6中 async 函数、await表达式 的基本用法
- Add text watermark to PHP image
- 过滤器(Filter)
- 作业:iptables防止nmap扫描以及binlog
- 【深入浅出玩转FPGA学习15----------时序分析基础】
- WEB安全基础 - - -漏洞扫描器
- 【Yugong Series】July 2022 Go Teaching Course 017-IF of Branch Structure
- DOM系列之scroll系列
猜你喜欢

mysql主从复制及读写分离脚本-亲测可用
![[In-depth and easy-to-follow FPGA learning 15---------- Timing analysis basics]](/img/a9/4c7a703a36a244394b586bfb42ab6b.png)
[In-depth and easy-to-follow FPGA learning 15---------- Timing analysis basics]

场景之多数据源查询及数据下载问题

什么是Promise?Promise的原理是什么?Promise怎么用?

作业:iptables防止nmap扫描以及binlog
Go study notes (84) - Go project directory structure

Mysql systemized JOIN operation example analysis

Regular expression password policy and regular backtracking mechanism bypass

【唐宇迪 深度学习-3D点云实战系列】学习笔记

【深入浅出玩转FPGA学习15----------时序分析基础】
随机推荐
Jetpack Compose learning (8) - State and remeber
作业:iptables防止nmap扫描以及binlog
Optimization of aggregate mentioned at DATA AI Summit 2022
限制字符绕过
加密传输过程
Adding, deleting, modifying and checking the foundation of MySQL
Shell programming of conditional statements
Neural Network (ANN)
IOT cross-platform component design scheme
【Yugong Series】July 2022 Go Teaching Course 017-IF of Branch Structure
DOM系列之 offset 系列
GO GOPROXY proxy Settings
Go 学习笔记(84)— Go 项目目录结构
BOM系列之Navigator对象
网络常用的状态码
【唐宇迪 深度学习-3D点云实战系列】学习笔记
Homework: iptables prevent nmap scan and binlog
SWM32 Series Tutorial 6 - Systick and PWM
What is Promise?What is the principle of Promise?How to use Promises?
ShardingSphere之读写分离(八)