Search code examples
c#unity3d-2dtools

Is it possible to subtract a Vector2


I'm trying to slightly change the velocity of a ball as it collides with objects, depending on the direction it is already travelling in, in a 2D game in Unity.

To find the direction in which the ball is travelling, I have been using

public Vector2 ballDirection;
public Vector2 lastPosition; 

void OnCollisionEnter2D(Collision2D boing)
{
    ballDirection = transform.position - lastPosition;
    lastPosition = transform.position;
}

This however throws up an error reading

Error CS0034 Operator '-' is ambiguous on operands of type 'Vector3' and 'Vector2'

The collision between the ball and any object prints as UnityEngine.Vector3

Is it indeed possible to subtract a Vector2 or would I be able to change the collision type to Vector2 somehow?


Solution

  • I think that you can simply cast the Vector3 variable to Vector2 (z is discarded)

    ((Vector2)transform.position) - lastPosition;
    

    or the Vector2 variable to Vector3 (z is set to zero):

    transform.position - ((Vector3)lastPosition);
    

    Could you please check whether it works for you?