如何使用Mathf.Clamp()限制玩家移动?

问题描述 投票:0回答:0

嗨,我正在制作一款游戏,玩家必须控制一个立方体。立方体在 x 轴上移动。使用水平输入轴。我面临的问题是我不希望立方体从屏幕中消失。我尝试使用 Mathf.Clamp() 函数来夹紧运动,但它不起作用。

这是代码:

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

public class PlayerControls : MonoBehaviour
{
    float xMovement;
    [SerializeField] private  float movingSpeed = 5f;
    [SerializeField] private float xRange = 5f;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        movement();
    }

    private void movement()
    {
        float clampedXpos = Mathf.Clamp(xMovement, -xRange, xRange);
        xMovement = Input.GetAxis("Horizontal");
        transform.Translate(clampedXpos * movingSpeed * Time.deltaTime, 0, 0);
       
    }
}

unity-game-engine monodevelop
© www.soinside.com 2019 - 2024. All rights reserved.