为什么我的代码在if语句外部更新了我的vel变量?

huangapple go评论53阅读模式
英文:

Why is my code updating my vel variable outside of an if statement?

问题

我创建了一个2D Unity项目,里面有一个圆圈。我试图通过点击、拖拽然后释放鼠标来让这个圆圈移动。我的代码在获取鼠标按下动作并读取鼠标位置后,会在我释放鼠标时再次获取鼠标位置。这部分代码可以正常工作,并为小球提供速度,使其朝一个方向移动。但是,即使在释放鼠标按钮后继续移动鼠标,它也会改变小球的速度。我无法弄清楚为什么会这样。

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

public class NewBehaviourScript : MonoBehaviour
{
    public Rigidbody2D rb;

    private Vector2 vel;

    public int div;

    private int mouseDown;

    private Vector2 mousePos;
    private Vector2 mousePos2;

    // Start is called before the first frame update
    void Start()
    {
        mouseDown = 0;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0) && mouseDown == 0)
        {
            mousePos = Input.mousePosition;
            mouseDown = 1;
        }
        if (Input.GetMouseButtonUp(0) && mouseDown == 1)
        {
            mousePos2 = Input.mousePosition;
            vel = new Vector2((mousePos2.x - mousePos.x) / div,
                (mousePos2.y - mousePos.y) / div);
            mouseDown = 0;
            print(vel);
        }
        rb.MovePosition(rb.position + vel * Time.deltaTime);
    }
}
英文:

I made a 2d unity project with a circle inside of it. I am trying to get the circle to move by clicking dragging then releasing with your mouse. My code gets the initial mouse down action and reads the mouse position then gets the mouse position when i release the mouse. This works and gives the ball a velocity which lets it move in a direction but when I continue to move the mouse even after releasing the button it changes the balls velocity. I cannot figure out why it is doing this.

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

public class NewBehaviourScript : MonoBehaviour
{
    public Rigidbody2D rb;

    private Vector2 vel;

    public int div;

    private int mouseDown;

    private Vector2 mousePos;
    private Vector2 mousePos2;

    // Start is called before the first frame update
    void Start()
    {
        mouseDown = 0;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0) && mouseDown == 0)
        {
            mousePos = Input.mousePosition;
            mouseDown = 1;
        }
        if (Input.GetMouseButtonUp(0) && mouseDown == 1)
        {
            mousePos2 = Input.mousePosition;
            vel = new Vector2((mousePos2.x - mousePos.x)/div,
                (mousePos2.y - mousePos.y)/div);
            mouseDown = 0;
            print(vel);
        }
        rb.MovePosition(rb.position + vel * Time.deltaTime);
    }
}

答案1

得分: 1

Note1: 在使用Unity物理引擎,特别是刚体(rigidbody)时,请确保在FixedUpdate中使用它。文档:这里

Note2: 如果与他人分享你的代码,请确保不要使用缩写的变量名。在第一眼看到代码时,很难知道你的意图。例如,veldiv

Note3: 如果你能更清楚地描述你试图实现的目标,那将会非常有帮助。例如,步骤1,你的输入动作是什么,步骤2,你希望看到的输出是什么。在提供的代码中,我假设球是朝着鼠标拖动方向而不是相反的,希望这符合你的需求。

Note4: Input.GetMouseButtonDown(0)Input.GetMouseButtonUp(0)只捕获一次,所以我认为你不需要单独的变量来计算鼠标点击次数(你的代码中的int mouseDown)。如果需要捕获按钮的按住状态,可以使用Input.GetMouseButton(0)

using UnityEngine;

public class CircleController : MonoBehaviour
{
    [SerializeField] private float _speed = 0.05f;
    private Rigidbody2D _rigidbody;
    private Vector3 _mouseDownPosition;
    private Vector3 _mouseUpPosition;

    void Start()
    {
        _rigidbody = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            _mouseDownPosition = Input.mousePosition;
            Debug.Log($"mouseDownPosition: {_mouseDownPosition}");
        }
        if (Input.GetMouseButtonUp(0))
        {
            _mouseUpPosition = Input.mousePosition;
            Debug.Log($"mouseUpPosition: {_mouseUpPosition}");
        }
    }

    void FixedUpdate()
    {
        Vector3 inputVector3 = _mouseUpPosition - _mouseDownPosition;
        _rigidbody.MovePosition(transform.position + inputVector3 * Time.deltaTime * _speed);
    }
}

我的场景设置

英文:

Note1: When working with Unity physics, namely rigidbody, make sure to use it in the FixUpdate. Documents: Here.

Note2: If you are sharing your code with others, make sure not to use abbreviated variable name. Its hard to know your intention in the code on first sight. e.g. vel , div.

Note3: It would help alot if you could describe what you are trying to archieve more clearly. Meaning,e.g. step1, what's your input action, step2, whats the output you wish to see. In the code provided, I made the assumption that the ball is drag towards your mouse drag direction instead of reverse, hope it matches to what you want.

Note4: Input.GetMouseButtonDown(0) and Input.GetMouseButtonUp(0) only captures once, so I don't think you need to have a seperate variable to count the mouseClick (your code -> int mouseDown). There is a Input.GetMouseButton(0) that will captures the holding of the button if that's what you need.

using UnityEngine;

public class CircleController : MonoBehaviour
{
    [SerializeField] private float _speed = 0.05f;
    private Rigidbody2D _rigidbody;
    private Vector3 _mouseDownPosition;
    private Vector3 _mouseUpPosition; 

    void Start()
    {
        _rigidbody = GetComponent&lt;Rigidbody2D&gt;();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            _mouseDownPosition = Input.mousePosition;
            Debug.Log($&quot;mouseDownPosition: {_mouseDownPosition}&quot;);
     
        }
        if (Input.GetMouseButtonUp(0))
        {
            _mouseUpPosition = Input.mousePosition;
            Debug.Log($&quot;mouseUpPosition: {_mouseUpPosition}&quot;);
        }
    }
    
    void FixedUpdate()
    {
        Vector3 inputVector3 = _mouseUpPosition - _mouseDownPosition;
        _rigidbody.MovePosition(transform.position + inputVector3 * Time.deltaTime * _speed);
    }
}

My Scene Setup

huangapple
  • 本文由 发表于 2023年6月19日 05:49:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定