unity2D横板开发Day2
一,动画:Animator和Animation
给游戏物体绑定Animator

给Animator绑定Controller并添加Animation

动画转变->右击->Make Transition,设置切换条件

通过调节Samples控制动画速率

二,镜头跟随
1,代码实现:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraControl : MonoBehaviour { public Transform player; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { this.transform.position = new Vector3(player.position.x, player.position.y, this.transform.position.z); } }
2,Cinemachine插件
下载:Window->PackageManager->Cinemachine 成功会出现下图所示

点击创建2D相机,会自动覆盖原相机

基础设置

Follow 选择跟随物体
Orthographic Size 调节相机大小
Screen X,Screen Y 分别调节相机x,y轴位置
Dead Zone Width 设置空白区域宽度,未超过该区域镜头不跟随
Dead Zone Height 设置空白区域高度,未超过该区域镜头不跟随

Extensions拓展插件
Confiner插件,给该插件绑定一个Polygon Collider 2D 则相机镜头不会超出该部分
如给背景设置一个Polygon Collider 2D(多边形碰撞体)并赋给Confiner插件,则游戏过程中镜头不会超过边界
三,今日代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { private Rigidbody2D rb; public float speed; public float jumpforce; public LayerMask ground; public Animator animator; public int cherryNum=0; // Start is called before the first frame update void Start() { rb = this.GetComponent<Rigidbody2D>(); } // Update is called once per frame void FixedUpdate() { Movement(); changeAnimation(); } //移动 void Movement() { float horizontalmove = Input.GetAxis("Horizontal"); float facedirection = Input.GetAxisRaw("Horizontal"); //角色移动 if (horizontalmove != 0) { rb.velocity = new Vector2(horizontalmove * speed, rb.velocity.y); animator.SetBool("isRun",true); } else { animator.SetBool("isRun", false); } if (facedirection != 0) { this.transform.localScale = new Vector3(facedirection, this.transform.localScale.y, this.transform.localScale.z); } //角色跳跃 if (Input.GetButtonDown("Jump")) { rb.velocity = new Vector2(rb.velocity.x, jumpforce); animator.SetBool("jumping", true); } } //动画切换 void changeAnimation() { if (rb.velocity.y < 0) { animator.SetBool("idle", false); animator.SetBool("jumping", false); animator.SetBool("falling", true); } else { animator.SetBool("idle", true); animator.SetBool("falling", false); } } //碰撞检测 private void OnTriggerEnter2D(Collider2D collision) { //收藏品销毁与数量计算 if(collision.tag == "Collection") { Destroy(collision.gameObject); cherryNum += 1; } } }
四,OnTriggerEnter2D
碰撞检测,该碰撞体需要勾选isTrigger
本Demo中需要检测是否碰撞到收藏品来进行销毁和加分操作
则通过添加修改游戏中收藏品Tag为“Collection”并使用该方法检测所碰物体tag是否为“Collection”来执行此操作

浙公网安备 33010602011771号