Vector3 in a 2D project?

First a general question. Is it better to ask questions in Udemy or GameDev.tv? I’m never quite sure where to put comments and questions. In this case I’m putting it in both.

Now to my coding question…

I wrote the code for this video before I watched Rick (attaching the ball to the paddle) but I did it with Vector3 rather than Vector2. The code works. My question is… is it bad practice to be coding with Vector3 in a 2D project? The advantage, in this particular case, is that I have only one line in Update() rather than 2 lines which might be more efficient. Here’s my code.

public class Ball : MonoBehaviour
{
    // config params
    // note to self: type "Paddle" is defined by the SCRIPT on paddle, not the name of the game object
    [SerializeField] Paddle paddle1;

    // state
    Vector3 paddleToBallVector;

    void Start()
    {
        paddleToBallVector = transform.position - paddle1.transform.position;
    }

    void Update()
    {
        transform.position = paddle1.transform.position + paddleToBallVector;
    }
}

This forum is better, or at least more monitored by others. As for your question, I don’t think it really matters, although someone may correct me and saying mathematically 2D is easier than 3D for the computer.

It for unity it is just 3D with a 2D perspective, and you may move things deeper to prevent collisions.

1 Like

Here’s the difference between the 2 update functions. In the first we are declaring a variable every update. That feels like something I’d want to avoid if I could, given that it’s happening 60 times a second or whatever the frame rate is. Do you know if that is something I should avoid or is it not a big deal?

    // using Vector2
    void Update()
    {
        Vector2 paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
        transform.position = paddlePos + paddleToBallVector;
    }

    // using Vector3
    void Update()
    {
        transform.position = paddle1.transform.position + paddleToBallVector;
    }

I would think in this case it doesn’t matter but you could declare a variable that is global so that you don’t have to re-create the variable every time and you’re just assigning a value to it. That would save some CPU cycles, but again I doubt it makes a difference in paddleball. But I’m trying to understand why it The second line would be problematic, the difference between the two is basically you’re working with vector3 so you don’t have to create a vector2. Right?

So if I look a bit and unity docs. They use current and new position vector. But that just seems messy. In the end just ignoring the Z position is not really a problem

1 Like

This topic was automatically closed after 13 days. New replies are no longer allowed.

Privacy & Terms