当前位置:网站首页>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);
}
}
}
边栏推荐
猜你喜欢
不用Swagger,那我用啥?
In-depth understanding of the auto-increment operator from two error-prone written test questions
ES 中时间日期类型 “yyyy-MM-dd HHmmss” 的完全避坑指南
Oracle has a weird temporary table space shortage problem
加密传输过程
DOM系列之 offset 系列
正则表达式密码策略与正则回溯机制绕过
Go 学习笔记(84)— Go 项目目录结构
MySQL数据库面试题总结(2022最新版)
web漏洞之需要准备的工作
随机推荐
C语言力扣第48题之旋转图像。辅助数组
PHP图片添加文字水印
Preparations for web vulnerabilities
Meeting OA project pending meeting, all meeting functions
Regular expression password policy and regular backtracking mechanism bypass
【唐宇迪 深度学习-3D点云实战系列】学习笔记
binglog log tracking: data backup and backup tracking
Basic usage of async functions and await expressions in ES6
MySQL数据库(基础)
Method for deduplication of object collection
Mysql systemized JOIN operation example analysis
(五)fastai应用
响应式布局与px/em/rem的比对
ELK部署脚本---亲测可用
对象集合去重的方法
pytorch双线性插值
BOM系列之history对象
ES 中时间日期类型 “yyyy-MM-dd HHmmss” 的完全避坑指南
MySQL triggers
DOM系列之 client 系列