【问题标题】:Move up and down depending on the position of the mouse when it clicks根据鼠标点击时的位置上下移动
【发布时间】:2018-07-12 16:45:04
【问题描述】:

我有点进退两难。我正在开发一个游戏,我需要做一些我不明白的事情。我有一个使用此脚本上下移动的对象:

    void FixedUpdate()
{
    if (canClick)
    {
        float moveVertical = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(0f, moveVertical, 0f);
        Tucan.GetComponent<Rigidbody2D>().velocity = movement * speed;
        Tucan.GetComponent<Rigidbody2D>().position = new Vector3
        (
            -7.5f,
            Mathf.Clamp(Tucan.GetComponent<Rigidbody2D>().position.y, boundary.yMin, boundary.yMax),
            0.0f
        );
    }
}

现在我想在单击鼠标 (0) 时执行此操作,如果 Mouse.y> 0 则对象向上移动,如果 Mouse.y 位置 则分别向下移动

    private void Update()
{
    Vector3 mouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    if (Input.GetMouseButton(0))
    {
        if (mouse.y > 0f)
        {

        }
        else
        {

        }
    }
}

如何执行与 FixedUpdate 相同的代码,在 Update 中运行它,但要进行检查。并且已经依赖于 Mouse.y。

【问题讨论】:

  • 您的意思是鼠标是否在对象上方? i 鼠标在屏幕中心上方?
  • 所以屏幕将它一分为二,当我点击向上时,它会向上移动,反之亦然

标签: c# unity3d


【解决方案1】:

只需将 WorldSpace 鼠标位置 Y 与您的游戏对象 Y 进行比较

void Update()
{
    Vector3 mouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    if (Input.GetMouseButton(0))
    {
        Vector3 movement;
        if (mouse.y > Tucan.transform.position.y)
        {
            movement = Vector3.up;
        }
        else
        {
            movement = Vector3.down;
        }


        Tucan.GetComponent<Rigidbody2D>().velocity = movement * speed;
    }
}

编辑

因为您想要分屏解决方案

所以屏幕将它分成两部分,当我点击向上时,它会向上移动 反之亦然

void Update()
{
    var mouse = Input.mousePosition;
    mouse.y -= Screen.height / 2;
    if (Input.GetMouseButton(0))
    {
        Vector3 movement;
        if (mouse.y > 0)
        {
            movement = Vector3.up;
        }
        else
        {
            movement = Vector3.down;
        }


        Tucan.GetComponent<Rigidbody2D>().velocity = movement * speed;
    }
}

【讨论】:

  • 它确实有效,我在发布之前先自己复制它
  • 但是我会做一个编辑,让它变成一个分屏的东西!
  • 不知道为什么,确实是不动对象
  • 我换了,速度变快了,什么都没有
  • 不知道边界值是什么,所以我删除了那些 ifs 并输入 255 而不是 maxSpeed 并且我的对象移动
猜你喜欢
  • 2019-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
  • 2015-11-05
相关资源
最近更新 更多