2D游戏知识点二、Unity 2D游戏主角基本功能和动画
地圖添加Tilemap Collider 2D
快速創建主角及動畫?
起個名字保存一下?
界面上已經有人物了,點擊運行,可以看到idle動畫,給人物idle添加Circle Collider 2d和Rigidbody 2D,然后將idle重命名為player,設置Rigidbody 2D的z軸鎖定,防止移動時翻跟頭
動畫拖不進去的解決辦法,不知道為什么,教程可以直接拖進去,我的就是不行,應該是沒找對方法,可以通過另種方法實現動畫制作
拖動所有素材到Hierarchy
起個名字
刪掉沒有的動畫等
修改playerAnimation動畫,run后期修改成了runing類型改成float了,方便動畫切換
把條件統統設置上去,并且動畫切換時間改為0
run->idle
idle->run
jump->idle
idle->jump
run->jump
jump->run
給主角添加腳本
安裝屏幕方向組件,assetstore搜索Joystick Pack添加到我的資源,導入到項目
添加Canvas并將Variable joystick拖動給Canvas
調整分辨率和Joystick位置
Cravity Scale重力修改為3方便快速下落
添加一個Background圖層
將地圖設置到Background圖層
將資源幅值給player中的腳本
代碼
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI;public class PlayerControler : MonoBehaviour {[SerializeField] private Rigidbody2D PlayerRd;[SerializeField] private Animator PlayerAnimator;public Collider2D PlayerCollider;public float Speed;public float Jumpforce;public LayerMask Ground;public VariableJoystick variableJoystick;// Start is called before the first frame updatevoid Start(){PlayerRd = GetComponent<Rigidbody2D>();PlayerAnimator = GetComponent<Animator>();}// Update is called once per framevoid Update(){Movement();SwithcAnim();}void Movement(){float horizontalMove = variableJoystick.Horizontal;float verticalMove = variableJoystick.Vertical;#region 設置PlayerRd.velocity = new Vector2(horizontalMove * Speed * Time.deltaTime, PlayerRd.velocity.y);PlayerAnimator.SetFloat("runing", Mathf.Abs(PlayerRd.velocity.x));//跳躍和落地if (verticalMove > 0.5f && ((PlayerCollider.IsTouchingLayers(Ground)))){PlayerRd.velocity = new Vector2(PlayerRd.velocity.x, Jumpforce);}if (horizontalMove > 0){transform.localScale = new Vector3(1, 1, 1);}else if (horizontalMove < 0){transform.localScale = new Vector3(-1, 1, 1);}#endregion}void SwithcAnim(){if (PlayerCollider.IsTouchingLayers(Ground)){PlayerAnimator.SetBool("jump", false);}else if(Mathf.Abs(PlayerRd.velocity.y) > 10){PlayerAnimator.SetBool("jump", true);}} }最終效果
有時走動會發現忽快忽慢,是因為碰撞器產生了向上的力后地面的摩擦力就小了,有一種比較簡單的解決辦法,就是直接改變player的位置,修改后的代碼
void Movement(){float horizontalMove = variableJoystick.Horizontal;float verticalMove = variableJoystick.Vertical;#region 設置PlayerRd.transform.position = new Vector2(horizontalMove * Speed * Time.deltaTime + PlayerRd.transform.position.x, PlayerRd.transform.position.y);PlayerAnimator.SetFloat("runing", Mathf.Abs(horizontalMove));//跳躍和落地if (verticalMove > 0.5f && ((PlayerCollider.IsTouchingLayers(Ground)))){PlayerRd.velocity = new Vector2(PlayerRd.velocity.x, Jumpforce);}if (horizontalMove > 0){transform.localScale = new Vector3(1, 1, 1);}else if (horizontalMove < 0){transform.localScale = new Vector3(-1, 1, 1);}#endregion}需要調整一下速度值
總結
以上是生活随笔為你收集整理的2D游戏知识点二、Unity 2D游戏主角基本功能和动画的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 万代南梦宫(中国)旗下数字娱乐、玩具娱乐
- 下一篇: java饲养员喂动物_做一个饲养员给动物