【问题标题】:How to move camera using joystick in Unity?如何在 Unity 中使用操纵杆移动相机?
【发布时间】:2017-12-05 04:59:15
【问题描述】:

我在 Unity 中使用操纵杆移动相机时遇到问题。我把这段代码写到我的操纵杆上

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;


public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler {

private Image bgImg;
private Image joystickImg;
private Vector2 pos;


private void Start()
{
    bgImg = GetComponent<Image>();
    joystickImg = transform.GetChild(0).GetComponent<Image>();
}


public virtual void OnDrag(PointerEventData ped)
{
    Vector2 pos;
    if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos))
    {
        pos.x = (pos.x * 2 + 1) / bgImg.rectTransform.sizeDelta.x;
        pos.y = (pos.y * 2 - 1) / bgImg.rectTransform.sizeDelta.y;


        pos = (pos.magnitude > 1.0f) ? pos.normalized : pos;

        // Move Joystrick IMG
        joystickImg.rectTransform.anchoredPosition = new Vector2(pos.x * (bgImg.rectTransform.sizeDelta.x / 3), pos.y * (bgImg.rectTransform.sizeDelta.y / 3));
    }
}

public virtual void OnPointerDown(PointerEventData ped)
{
    OnDrag(ped);
}

public virtual void OnPointerUp(PointerEventData ped)
{
    pos = Vector2.zero;
    joystickImg.rectTransform.anchoredPosition = Vector2.zero;
}

public float Horizontal()
{
    if (pos.x != 0)
    {
        return pos.x;   
    }
    else
    {
        return Input.GetAxis("Horizontal");
    }
}

public float Vertical()
{
    if (pos.y != 0)
    {
        return pos.y;
    }
    else
    {
        return Input.GetAxis("Vertical");
    }
}
}

这段代码运行良好,动态返回 Vector2(x,y)。所以,现在我想使用这个操纵杆和这些坐标来移动相机(改变位置 X,Y)。你知道怎么做吗?每个人都展示了如何移动立方体或球体,而无处可移如何平移相机......

【问题讨论】:

    标签: c# android unity3d


    【解决方案1】:

    相机的行为与场景中的任何其他游戏对象一样 你平移、旋转、缩放(不会显示)

    因为它有 Transform 组件。

    【讨论】:

      【解决方案2】:

      这可以通过Translate 函数轻松完成

      Camera.main.transform.Translate(pos, Space.World);
      

      您还需要将其乘以一个数字(速度)和Time.deltaTime,以确保每个设备上的运动都相同。

      所以,代码应该是这样的:

      private Vector2 pos;
      public float moveSpeed = 100f;
      

      然后,在您的OnDragUpdate 函数中:

      Vector3 newPos = new Vector3(pos.x * moveSpeed, pos.y * moveSpeed, 0);
      newPos *= Time.deltaTime;
      
      Camera.main.transform.Translate(newPos, Space.World);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-26
        • 2019-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多