【问题标题】:moving object with mouse but not to the where mouse pointer is用鼠标移动对象但不移动到鼠标指针所在的位置
【发布时间】:2019-07-10 13:12:40
【问题描述】:

场景:

您好,我正在尝试使用鼠标控制沿 X 和 Z 轴的孔,但不希望孔移动到鼠标位置

平面 m_Plane;

private Vector3 newmousepos;


void Start()

{

    m_Plane = new Plane(Vector3.up, transform.position);

}

void Update()

{
    if (Input.GetMouseButton(0))

    {

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

          float enter = 0.0f;

          if (m_Plane.Raycast(ray, out enter))

           {
               //Get the point that is clicked
               Vector3 hitPoint = ray.GetPoint(enter);

              transform.position = 
              Vector3.Lerp(transform.position,hitPoint,Time.deltaTime*5f);

           }  

    }

【问题讨论】:

  • 你说你不希望它移动到鼠标上,那你到底需要它做什么?
  • 我猜你希望它以与鼠标相同的模式移动?所以如果鼠标移动 x+5 孔应该移动 x+5?
  • 你不需要光线投射。而是使用 Input.GetAxis
  • 看代码,我觉得我的猜测不正确..?我认为 OP 的 lerp 有问题?由于 lerp 操作不正确,它可能会立即传送到他的位置。
  • 我的意思是,当指针在场景中的随机位置时,我只想用鼠标控制孔,但我不知道如何避免孔移动到鼠标位置跨度>

标签: c# unity3d axis mouse-position


【解决方案1】:

编辑:基于新信息的新答案

我将保留旧答案,因为如果没有它,代码将无法正常工作,如果“向鼠标位置移动”将是所需的行为,如标题所示。

问题

您试图让对象进行与鼠标相同的移动,但您编写的代码采用鼠标的位置,而不是鼠标的移动,然后朝它移动。

解决方案

您必须检查鼠标的轴,并将该移动方向应用于对象,例如:

float speed = 5f;
void Update()
{
    if (Input.GetMouseButton(0))
    {
        var moveDirection = new Vector3(Input.GetAxis("Mouse X"), 0, Input.GetAxis("Mouse Y"));
        transform.position += moveDirection * speed * Time.deltaTime;
    }
}


旧答案

问题

我猜你的 Lerp 没有做你想做的事,因为代码只会执行一次,并且将你的位置设置为 Time.deltaTime*5,它应该大约是 0.9,这意味着 90%从transform.position 到hitPoint 的距离。更多关于乐平的信息,请阅读the documentation:

Vector3 Lerp(Vector3 a, Vector3 b, float t);

  • 当 t = 0 时:返回 a。
  • 当 t = 1 时返回 b。
  • 当 t = 0.5 时,返回 a 和 b 之间的中间点。

解决方案

我认为一个简单的Vector3.MoveTowards 对你有用:

Vector3 hitPoint;
float speed = 5;

void Update()
{
    if (Input.GetMouseButton(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        float enter = 0.0f;

        if (m_Plane.Raycast(ray, out enter))
        {
            hitPoint = ray.GetPoint(enter);
            transform.position = Vector3.MoveTowards(transform.position, hitPoint, speed * Time.deltaTime);
        }
    }
}

【讨论】:

  • 感谢您的帮助,但对象仍会移动到鼠标位置
  • 我不确定你到底想要什么,你想确认你希望对象做与鼠标相同的运动,但相对于它自己的位置,而不是鼠标?
  • 我编辑了我的答案以包含该场景的答案。
  • 很抱歉我无法解释清楚,假设您可以将手指放在屏幕的特定坐标上,并在 X 轴和 Z 轴沿场景控制孔对象。我发现这个游戏和我要找的东西很相似play.google.com/store/apps/details?id=com.h8games.blocksbuster
  • 我是否应该解释一下您没有确认我的问题是我误解的事实?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多