Reputation: 1
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 OnMouseDown()
{
difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
}
private void OnMouseDrag()
{
transform.position = (Vector2) Camera.main.ScreenToWorldPoint(Input.mousePosition) - difference;
}
}
Here is a picture of the error:
Upvotes: -1
Views: 86
Reputation: 90679
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
difference
to a Vector3
and use the Vector3 - Vector3
operatorCamera.main.ScreenToWorldPoint(Input.mousePosition)
to a Vector2
and rather use the Vector2 - Vector2
operatorLong 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;
Upvotes: 1
Reputation: 111
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.
Upvotes: 0