效果图如下:

完整脚本代码如下:

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

public class L15_Player : MonoBehaviour
{
    private float speed = 0.1f;
    public float MaxPointX;
    public float MinPointX;
    public float MaxPointY;
    public float MinPointY;
    void Start()
    {
        
    }

    void Update()
    {
        InputManagerMove();
    }
    private void InputManagerMove()
    {
        //水平方向玩家的操作程度 左-1 右1 中间有过度
        //GetAxisRaw 不平滑
        float h = Input.GetAxis("Horizontal");
        //水平方向玩家的操作程度 左-1 右1 中间有过度
        float v = Input.GetAxis("Vertical");
        if (h!= 0 || v!=0)
        {
            //X超过右边界,并且你还在往右边移动
            if (h> 0 && transform.position.x >= MaxPointX)
            {
                h = 0;
            }
            else if (h < 0 && transform.position.x <= MinPointX)
            //X超过左边界,并且你还在往左边移动
            {
                h = 0;
            }
            //Z超过上边界,并且你还在往上边移动s
            if (v > 0 && transform.position.z >= MaxPointY)
            {
                v = 0;
            }
            else if (v < 0 && transform.position.z <= MinPointY)
            //X超过下边界,并且你还在往下边移动
            {
                v = 0;
            }
            Debug.Log("H:" + h);
            Debug.Log("V:" + v);
            //没有超过边界
            transform.position += new Vector3(h, 0, v) * speed;
        }
    }
     
}
 

Logo

分享前沿Unity技术干货和开发经验,精彩的Unity活动和社区相关信息

更多推荐