【问题标题】:unity 4.6 slider player movementunity 4.6 滑块播放器移动
【发布时间】:2015-01-28 11:07:01
【问题描述】:

我正在使用新的 UI 4.6 系统在 Unity 中工作。

基本上我有一个非常简单的方法来计算玩家的移动(它只在 x 轴上移动)。因此,我目前只使用“水平”来获取运动。

我需要一种将玩家移动的值连接到滑块的方法,这样当你向左拖动它时它会向左移动,当你离开时它会停止移动,右侧也是如此。

我仍然是编程新手,并且已经四处寻找粗略的答案,但我很挣扎。

以下是我可以移动玩家的两种方式:第一种是我最近尝试使用速度但后来迷路了,因为它只会根据 -1 或 1 的值向玩家发送 1 种方式。我在 FixedUpdate 函数中调用以下语句。

    public void Movement(float horizontalInput)
{
    //Stores the velocity in a V3.
    Vector3 moveVel = myBody.velocity;
    //The x axis is the value passed intimes by movespeed.
    moveVel.x = horizontalInput * moveSpeed;
    //The value from the v3 is stored back into velocity.
    myBody.velocity = moveVel;
}

public void StartMoving(float horizontalInput)
{
    hozInput = horizontalInput;
}

在尝试获得移动类型的运动之前,我只是在使用这个:

        Vector3 newPosition = transform.position;
    newPosition.x += Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
    transform.position = newPosition;

这是移动角色的一种非常简单的方法,但我不确定是否可以将其分配给滑块。

我知道这些方法必须是公共无效的,UI 对象才能访问它们等,它只是将变量分配到我正在努力解决的正确位置。

非常感谢您的宝贵时间。

【问题讨论】:

  • 所以你想要一个滑块来代表一个角色在屏幕上的水平位置?或者你想要一个滑块来控制它的速度?
  • 我想用滑块控制位置。想象一个太空侵略者游戏,角色如何从左向右移动。就像那样,但使​​用滑块。感谢您的回复。

标签: c# user-interface unity3d game-physics


【解决方案1】:

我可以建议使用这样的东西。

  public class TouchPad : MonoBehaviour, IPointerUpHandler, IPointerDownHandler, IDragHandler 
    {
        public Vector2 virtualAxes;

        private Vector2 imagePad;
void Start()
    {
        imagePad = GetComponent<RectTransform>().sizeDelta;
    }
public void OnDrag(PointerEventData data)
    {
        imageColor.color = new Color (1f, 1f, 1f, 1f);

        int deltaPositionX = (int)(data.position.x - transform.position.x);
        deltaPositionX = Mathf.Clamp (deltaPositionX, -(int)(imagePad.x/2), (int)(imagePad.x/2));

        int deltaPositionY = (int)(data.position.y - transform.position.y);
        deltaPositionY = Mathf.Clamp (deltaPositionY, -(int)(imagePad.y/2), (int)(imagePad.y/2));

        virtualAxes = new Vector2 (deltaPositionX / (imagePad.x/2), deltaPositionY / (imagePad.y/2));
    }

    public void OnPointerUp(PointerEventData data)
    {
        virtualAxes = Vector2.zero;
        imageColor.color = new Color (1f, 1f, 1f, 0.15f);
    }

    public void OnPointerDown(PointerEventData data)
    {

    }

然后你可以使用类似的东西来控制它。

public class ControlPad : MonoBehaviour 
{
    public TouchPad aPad;


    public float speed = 5f;
    public float speedRotate = 150f;

    void Update ()
    {
        transform.Translate (aPad.virtualAxes.x* Time.deltaTime * speed, 0 ,0f);

    }   

}

现在您可以简单地创建一个与滑块一样大的 UI 元素,当您用手指或鼠标在滑块上拖动时,您将在 x 轴上移动一个对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 2018-05-08
    • 1970-01-01
    相关资源
    最近更新 更多