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);
        }

    }
}

 

转载于:https://www.cnblogs.com/yueqingli/p/10119351.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值