c# - 用鼠标移动对象但不移动到鼠标指针所在的位置

标签 c# unity3d axis mouse-position

场景: scene image

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

平面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);

           }  

    }

最佳答案

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

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

问题

您试图让对象做与鼠标相同的运动,但是您编写的代码采用鼠标的位置,而不是鼠标的移动,并向它移动。

解决方案

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

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.positionhitPoint 的距离。有关 Lerping 的更多信息,请阅读 the documentation :

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

  • When t = 0: returns a.
  • When t = 1 returns b.
  • When t = 0.5 returns the point midway between a and 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);
        }
    }
}

关于c# - 用鼠标移动对象但不移动到鼠标指针所在的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56971508/

相关文章:

c# - 更改页眉高度/大小 Winform

c# - 如何查找 PDF 中所有出现的特定文本并在上方插入分页符?

c# - 按下键时在两种颜色之间切换

java - 策略异常 : None of the policy alternatives can be satisfied in WCF Service Call

java - Prolog SAXParserException 中不允许内容

c# - 如何在Azure函数中绑定(bind)到MessageSender?

c# - 解构是暧昧的

c# - 使用 PlayerPrefs 的 Unity Highscore 无法正常工作

c# - 即使调用更改时 bool 仍然为 false

javascript - D3 条形图 Axis 怪癖