当前位置:网站首页>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);
}
}
}
边栏推荐
- ShardingSphere之垂直分库分表实战(五)
- 从两个易错的笔试题深入理解自增运算符
- TypeScript在使用中出现的问题记录
- 【Multithreading】
- MySQL table design for message queue to store message data
- A complete guide to avoiding pitfalls for the time-date type "yyyy-MM-dd HHmmss" in ES
- 【多线程】
- 【愚公系列】2022年07月 Go教学课程 013-常量、指针
- encrypted transmission process
- 小程序-全局数据共享
猜你喜欢
DNS resolution process [visit website]
论文理解:“Designing and training of a dual CNN for image denoising“
程序员工作三年攒多少钱合适?
Shell programming of conditional statements
MySQL grant statements
C language force buckles the rotating image of the 48th question.auxiliary array
Asser uses ant sword to log in
Understand from the 11 common examples of judging equality of packaging types in the written test: packaging types, the principle of automatic boxing and unboxing, the timing of boxing and unboxing, a
pytorch bilinear interpolation
MySQL master-slave replication and read-write separation script - pro test available
随机推荐
Kotlin协程:协程上下文与上下文元素
过滤器(Filter)
IOT cross-platform component design scheme
Optimization of aggregate mentioned at DATA AI Summit 2022
MySQL Series 1: Account Management and Engine
h264和h265解码上的区别
ShardingSphere之未分片表配置实战(六)
不用Swagger,那我用啥?
xss bypass: prompt(1)
从两个易错的笔试题深入理解自增运算符
从笔试包装类型的11个常见判断是否相等的例子理解:包装类型、自动装箱与拆箱的原理、装箱拆箱的发生时机、包装类型的常量池技术
DNS resolution process [visit website]
Error occurred while trying to proxy request项目突然起不来了
【952. 按公因数计算最大组件大小】
【c语言课程设计】C语言校园卡管理系统
SWM32系列教程6-Systick和PWM
解决:Parameter 0 of method ribbonServerList in com.alibaba.cloud.nacos.ribbon.NacosRibbonClientConfigu
Add text watermark to PHP image
unity2D横版游戏教程4-物品收集以及物理材质
ELK部署脚本---亲测可用