【问题标题】:Unity2D How do i get the main camera to move up on the Y axis continuously after i left mouse click?Unity2D单击鼠标左键后如何使主摄像机在Y轴上连续向上移动?
【发布时间】:2019-03-10 02:37:02
【问题描述】:

只有在单击鼠标左键后,我才试图让我的主摄像头在 Y 轴上缓慢向上移动。

这是我目前的代码。

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

public class CameraPanUp : MonoBehaviour
{
    public float speed = 5f;
    public Transform target;

    Vector3 offset;

// Start is called before the first frame update
void Start()
{
    offset = transform.position - target.position;
}


// Update is called once per frame
void FixedUpdate()
{
    Vector3 targetCamPos = target.position + offset;
    transform.position = Vector3.Lerp(transform.position, targetCamPos, speed * Time.deltaTime);

    if (Input.GetMouseButtonDown(0))
    {

    }
}

}

我不确定在上面的 if 语句中应该放什么。我之前尝试过使用transform.Translate,每次左键单击时它都会使相机以小幅度向上移动。这是为什么?任何帮助将不胜感激。

【问题讨论】:

  • 改成Input.GetMouseButton(0)只要按住鼠标按钮,相机就会向上移动

标签: unity3d


【解决方案1】:

一种选择是使用协程:

Coroutine moveCoroutine;
IEnumerator StartMovingUp() {
  float moveSpeed = 2f;
  while(true) {
    transform.Translate(0, moveSpeed * Time.deltaTime, 0);
    yield return null;
  }
}
void Update() {
  if (Input.GetMouseButtonDown(0) && moveCoroutine == null) {
    moveCoroutine = StartCoroutine(StartMovingUp());
  }
}

另一个是在Update 函数中使用状态字段。任何更多可能会使代码过于复杂。

bool isMovingUp;
float moveSpeed = 2f;
void Update() {
  if (Input.GetMouseButtonDown(0)) {
    isMovingUp = true;
  }
  if (isMovingUp) {
    transform.Translate(0, moveSpeed * Time.deltaTime, 0);
  }
}

【讨论】:

    猜你喜欢
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    相关资源
    最近更新 更多