Home > front end >  Operator `-` is amigues on operands of type `Vector2` and `Vector3`
Operator `-` is amigues on operands of type `Vector2` and `Vector3`

Time:08-26

This is my second time posting about this code as I keep running into errors as I use it. I originally make this from a tutorial but idk what is wrong with it. I have not really been able to try anything as I am a newbie dev and just don't know what to do

public class Draggable : MonoBehaviour
{
    Vector2 difference = Vector2.zero;
    private void onm ouseDown()
    {
        difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
    }

    private void onm ouseDrag()
    {
        transform.position = (Vector2) Camera.main.ScreenToWorldPoint(Input.mousePosition) - difference;
    }
}

Here is a picture of the error:

CodePudding user response:

You need to change the Vector2 cast to

transform.position = ((Vector2) Camera.main.ScreenToWorldPoint(Input.mousePosition)) - difference;

Note the extra pair of wrapping parenthesis.

What is happening is that originally you were doing

transform.position = (Vector2) (Camera.main.ScreenToWorldPoint(Input.mousePosition) - difference);

This didn't work because ScreenToWorldPoint returns a Vector3 while difference is a Vector2. Now you will be casting the result of ScreenToWorldPoint to a Vector2 before the subtraction operation.

CodePudding user response:

Unity has implicit operator conversion between Vector2 and Vector3.

Camera.main.ScreenToWorldPoint(Input.mousePosition)

returns a Vector3.

difference

is a Vector2.

- is only implemented with either Vector2 - Vector2 or Vector3 - Vector3.

=> The compiler doesn't know whether

  • it should rather convert the difference to a Vector3 and use the Vector3 - Vector3 operator
  • or it should convert the result of Camera.main.ScreenToWorldPoint(Input.mousePosition) to a Vector2 and rather use the Vector2 - Vector2 operator

Long story short it seems you would want the second option so you need to explicit type cast not the result of the - but rather

(Vector2) Camera.main.ScreenToWorldPoint(Input.mousePosition)

so

transform.position = ((Vector2) Camera.main.ScreenToWorldPoint(Input.mousePosition)) - difference;
  • Related