Unity 2D角色移動方式(二)


一,使用velocity方法移動角色;

二,使用localScale,使x等於負數實現圖片反轉;

三,m_rg.velocity = 數值*方向;

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    private Rigidbody2D m_rg;

    public float MoveSpeed;


    void Start () {

        m_rg = gameObject.GetComponent<Rigidbody2D>();

    }
    
    // Update is called once per frame
    void Update () {
        //------------------Input.GetAxisRaw沒有小數值,只有整數,不會產生緩動------------------
        //角色水平移動
        //按住D鍵,判斷如果大於0,則向右開始移動
        if (Input.GetAxisRaw("Horizontal") > 0)
        {
            m_rg.velocity = new Vector2(MoveSpeed, m_rg.velocity.y);

            //設置自身縮放的值
            transform.localScale = new Vector2(1f,1f);
        }
        //角色水平移動
        //按住A鍵,判斷如果小於0,則向左開始移動
        else if (Input.GetAxisRaw("Horizontal") < 0)
        {
            m_rg.velocity = new Vector2(-MoveSpeed, m_rg.velocity.y);

            //如果new Vector2(-1f, 1f)  x值為負數,則圖片進行反轉顯示
            transform.localScale = new Vector2(-1f, 1f);
        }
        else
        //角色水平移動
        //松開按鍵,判斷如果等於0,則停止移動
        {
            m_rg.velocity = new Vector2(0, m_rg.velocity.y);
        }

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM