SDL subtracting vectors

Pages: 12
Hi guys,

so as you can tell by my recent posts I'm messing around with SDL following a couple of tutorials on collisions and vectors/movement,

so to subtract a vector is pretty simple, we want to subtract A from B or B-A let's say we have vector A (x = 40, y = 100) and Vector B ( x = 20, Y = 80 ) from what I have read we flip the sign of vector A so vector A becomes ( x = -40 , y = -100) and we add vector A to B which gives us a new vector (20+(-40),80+(-100)) = (-20,-180) - already I feel this is wrong because in an engine like SDL we can not represent this vector as SDL grid or axis system is represented with positive integers.

in my example I have two rectangles - a black one A, and a red one B, to find the distance between them I can create a distance vector, what I did was flip the sign of the black rectangles x and y values and added it to the red rectangles x and y values, but if you do the math you see that the new vectors x value = 380 and y value = -200

problem is I can't represent this in SDL, I feel like I'm doing something horribly wrong

here is an image of the rectangles on screen - https://ibb.co/j4r00QC

Thanks


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147


#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

using namespace std;

SDL_Renderer* renderer;
SDL_Window* window;
SDL_Texture* texture;
SDL_Surface* surface;
SDL_Event event;


class Vector2{

   public:
       int x;
       int y;

       Vector2(int x,int y): x(x),y(y){}
       Vector2(){x = 0;y = 0;}

       void add(Vector2& other){

          x += other.x;
          y += other.y;
       }

       void scale(double scalar){

          x*=scalar;
          y*=scalar;
       }

};

Vector2 addVectors(const Vector2& one,const Vector2& two){

   Vector2 difference;
   difference.x = one.x + two.x;
   difference.y = one.y + two.y;
   return difference;
}

class BlackRect{

  public:
      bool objectLeft = false;
      bool objectRight = true;
      Vector2 vec;
      SDL_Rect spriteOneRect;
      SDL_Surface* spriteOneSurface;
      SDL_Texture* spriteOneTexture;


      BlackRect(int x,int y,string fileName){

         vec.x = x;
         vec.y = y;
         spriteOneSurface = IMG_Load(fileName.c_str());
         spriteOneTexture = SDL_CreateTextureFromSurface(renderer,spriteOneSurface);
         spriteOneRect.x = x;
         spriteOneRect.y = y;
         SDL_QueryTexture(spriteOneTexture,NULL,NULL,&spriteOneRect.w,&spriteOneRect.h);
      }
      BlackRect(){

        vec.x = 250;
        vec.y = 250;
      }

      void update(){

        spriteOneRect.x = vec.x;
        spriteOneRect.y = vec.y;
      }

};


void render(BlackRect& br,BlackRect& rr){

    SDL_RenderClear(renderer);
    SDL_SetRenderDrawColor(renderer,255,255,255,255);
    SDL_RenderCopy(renderer,br.spriteOneTexture,NULL,&br.spriteOneRect);
    SDL_RenderCopy(renderer,rr.spriteOneTexture,NULL,&rr.spriteOneRect);
    SDL_RenderPresent(renderer);
}



int SDL_main(int argc,char* argv[]){

   init(); // init not included in snippet
   bool quit = false;
   bool jumping = false;
   BlackRect br(20,400,"blockone.png");
   BlackRect rr(400,200,"blockoneRed.png");

   Vector2 gravity(0,1);
   Vector2 velocity(2,-20);

   Vector2 minusTwoPos(-20,-400);
   Vector2 difference = addVectors(rr.vec,minusTwoPos);
   cout << difference.x << " y == " << difference.y << endl;


    while(true)
    {
        while(SDL_PollEvent(&event))
        {
            if(event.type == SDL_QUIT)
            {
                cleanUp();
                return 0;
            }

            if(event.type == SDL_KEYDOWN)
            {

                int key = event.key.keysym.sym;
                if(key == SDLK_b)
                    moveObject(br);
                else if(key == SDLK_c){
                    br.vec.add(difference);
                    br.update();
                
                }
            }

        }

        if(jumping)
        {
            br.vec.add(velocity);
            br.update();
            velocity.add(gravity);
            jumpSecond(br,400,jumping,velocity);
        }
        render(br,rr);
        SDL_Delay(20);
   }
   cleanUp(); // clean up not included in snippet 
}
First of all, the sum of 2 vectors should never be called "difference".
If you want to subtract a vector from another, create a function called subractVectors. Then in that function, negate the second vector and add them. Or more simply, just subtract the constituent members (rather than negating and adding).

What do you mean by "distance"? In colloquial terms, distance is just a magnitude. Chicago is 300 miles from St. Louis.

Here, distance is a vector. The red box is 50 pixels below and 35 pixels to the left of the black box. So, the positive/negative values indicate in which direction the distance goes.

If all you want is the magnitude, take the absolute values of the components.
problem is I can't represent [(380, -200)] in SDL, I feel like I'm doing something horribly wrong
Why can't you display such a vector? Suppose that the vector was actually (380, 200). How would you display it?
Here, distance is a vector. The red box is 50 pixels below and 35 pixels to the left of the black box. So, the positive/negative values indicate in which direction the distance goes.


so y = 380 means that the black box is 380 pixels below( since the further you go down in SDL the greater the Y val ) and the red box and x = -200 means pixels to the left of the red box?

Also once I have this vector, how would I move the red box until it meets/collides the with the black box, or should I say how can I move the black box along this distance vector? would this relate to the magnitude of the vector?

Why can't you display such a vector? Suppose that the vector was actually (380, 200). How would you display it?


You could display (380,200) but (380,-200) would be off the screen?
Last edited on
I ask again: How would you display the vector? Imagine that the vector is (380, 200) and draw on the screenshot you posted earlier how you think it should appear.
@Helios
https://ibb.co/hLsV542 - that is where approx (380,200) vector would be, am I on the right track? ( note :: I made a small mistake the tail of the arrow should be at the very corner so at the origin x = 0, y = 0)

so y = 380 means that the black box is 380 pixels below( since the further you go down in SDL the greater the Y val ) and the red box and x = -200 means pixels to the left of the red box?


this seems to be correct, but again I'm wondering how I would move the black rectangle along that vector from red rectangle to black rectangle

thanks
Last edited on
Why would you display it like that? Consider this example:
https://ibb.co/B2xDkQc
How is that a useful way of conveying the relevant information, especially, as you've already pointed out, some vectors can't be displayed in this manner? Why not take advantage of the fact that vectors don't have an origin and instead display it like this?
https://ibb.co/vXJpTGN
Like that, you can even display vectors with negative components:
https://ibb.co/BwSVjZN
very true, good points but in the last images I'm guessing the origin ( or maybe I should just say tail in this case? ) is the red rectangles x,y value though technically right?

From all the tutorials I have read online though they say that in games programming there generally is always an origin and that will be the start point or very corner of the screen point (0,0), this isn't always true?
Last edited on
As I said previously, a vector is just a pair (or triple, or tuple) of numbers. You can choose to interpret it however you want.

From all the tutorials I have read online though they say that in games programming there generally is always an origin and that will be the start point or very corner of the screen point (0,0), this isn't always true?
No, not in the least. A vector could be storing a character's position in the game world relative to an arbitrary position in it. This arbitrary position will generally be completely unrelated to the screen, and may in fact not be visible in the screen or its position may change depending on the position and orientation of the camera.
Rather than position, a vector could be storing a rotation, which cannot be linked back to any location on the screen. Even more abstractly, a vector may not even make sense spatially. A vector might represent a color, for example.
Last edited on
that makes sense, that is very true especially in the case where you may want to know where an object is from another point on the screen instead of the origin, but a side question; when is knowing or using the origin as a reference point with vectors useful or appropriate?

yeah that is one example I have seen before and honestly makes no sense to me , I have no idea how a vector can represent a color.
Last edited on
I have no clue how a vector can represent a color.
It can be an <R, G, B> value. Or, <Hue, Saturation, Value>, <C, M, Y, K>, etc.

Worrying about the origin is a problem of coordinate systems, not necessarily vectors.

(1, 1) is just a value. Depending on your coordinate system, it might be the top-right of the screen (e.g. OpenGL), or it might mean something else. (0, 0) is just another value. Perhaps it means the center of the screen, or the top-left of the screen, or it represents some world-space coordinate that is completely independent of where it's drawn on the screen, as helios mentioned (there would be some translation from "world coordinates" to "screen coordinates").

Treating the world coordinate system the same as the screen coordinate system is fine for a simple test program, but once you start introducing large world maps, scrolling, or zooming, then you need to start translating world coordinates to screen coordinates (and vice-versa).
Last edited on
when is knowing or using the origin as a reference point with vectors useful or appropriate?
By definition, a vector is always relative to the origin. If the question is "when does it make sense to make the origin relative to a fixed position of the screen?" then the answer is: typically you will only have screen-space vectors as the last step prior to drawing on the screen, or in the reverse, when the user clicks on the screen and you want to find an object in world-space that is visible at the position the user clicked.

It can be an <R, G, B> value.
More concretely, suppose you have a red light, a green light, and a blue light, that are all shining onto a white wall. If you have an (r, g, b) vector where each component is the voltage applied to each light, you will find that (1, 0, 0) makes the wall appear red, (1, 0, 1) makes it appear magenta, and (1, 1, 1) makes it appear white.
when is knowing or using the origin as a reference point with vectors useful or appropriate?
By definition, a vector is always relative to the origin. If the question is "when does it make sense to make the origin relative to a fixed position of the screen?" then the answer is: typically you will only have screen-space vectors as the last step prior to drawing on the screen, or in the reverse, when the user clicks on the screen and you want to find an object in world-space that is visible at the position the user clicked.


Worrying about the origin is a problem of coordinate systems, not necessarily vectors.

(1, 1) is just a value. Depending on your coordinate system, it might be the top-right of the screen (e.g. OpenGL), or it might mean something else. (0, 0) is just another value. Perhaps it means the center of the screen, or the top-left of the screen, or it represents some world-space coordinate that is completely independent of where it's drawn on the screen, as helios mentioned (there would be some translation from "world coordinates" to "screen coordinates").


Oh ok but that origin can change right? for example the origin could be the corner of the screen, or the origin could be a certain fixed point on the screen such as the examples Helios gave in the last and penultimate images where the origin was the x,y coordinates of the red rectangle , and this definition would still hold true,correct?

I should probably have phrased that question a little better, probably was a little too open to interpretation, so here is my second shot: When would using the origin as the the corner of the screen or x = 0, y = 0 be useful or of course necessary?

thanks
Last edited on
Oh ok but that origin can change right? for example the origin could be the corner of the screen, or the origin could be a certain fixed point on the screen
I'm not entirely sure I understand what you're asking, but you typically don't want to change what the origin is after you've determined the value of a vector, because what you're interested in is the meaning of the vector. If you say "the enemy is 100 m to the South!", 100 m to the South of your position and 100 m to the South of the gates may be two very different positions.

When would using the origin as the the corner of the screen or x = 0, y = 0 be useful or of course necessary?
typically you will only have screen-space vectors as the last step prior to drawing on the screen, or in the reverse, when the user clicks on the screen and you want to find an object in world-space that is visible at the position the user clicked.
I'm not entirely sure I understand what you're asking, but you typically don't want to change what the origin is after you've determined the value of a vector, because what you're interested in is the meaning of the vector. If you say "the enemy is 100 m to the South!", 100 m to the South of your position and 100 m to the South of the gates may be two very different positions.


but in terms of games programming what is the origin? it is the starting point (0,0)?, can the origin change or will it always be at 0,0 , for example let's say you have a checkpoint let's be vague and assume there is only one checkpoint in the game. The checkpoint is at (200,200) pixels on the screen, can we consider this checkpoint as the origin?

Why not take advantage of the fact that vectors don't have an origin and instead display it like this?


By definition, a vector is always relative to the origin.


does this not contradict?

sorry if I'm misinterpreting all of this, I think I'm on the right path ( at least I hope I am )

does this not contradict?
Sorry for the confusion. I used the word "origin" in two different senses.

First in the loose colloquial sense:
"Why not take advantage of the fact that vectors don't have an origin a {source|initial point} and instead display it like this?"

I was later forced to use the word "origin" in the strict mathematical sense because you used it:
"By definition, a vector is always relative to the origin zero."

what is the origin? it is the starting point (0,0)?
"Origin" and "element zero" (the vector whose coordinates are all zero) are synonyms. The origin is simply the point which the vector is relative to. For example, when someone says "the altitude is 1000 m", it's implied that the zero is sea level. When someone gives a GPS coordinate, it's implied that the zero is roughly 620 km off the coast of Ghana, in Africa.

can the origin change or will it always be at 0,0
By definition, the origin is zero, but you can make "zero" mean anything you want. (0, 0) can mean the top-left corner of the screen, or the center, or anything else. As long as your values and operations are consistent, it doesn't matter what "zero" refers to.
Does this answer your other question?
for example let's say you have a checkpoint let's be vague and assume there is only one checkpoint in the game. The checkpoint is at (200,200) pixels on the screen, can we consider this checkpoint as the origin?
Origin" and "element zero" (the vector whose coordinates are all zero) are synonyms. The origin is simply the point which the vector is relative to. For example, when someone says "the altitude is 1000 m", it's implied that the zero is sea level. When someone gives a GPS coordinate, it's implied that the zero is roughly 620 km off the coast of Ghana, in Africa.


That makes sense so the origin is the point in which all vectors are relative too. Another thing though and let's use the rectangles as examples, as you can see both rectangles are in a fixed position and not moving ie they are static. Both the black rectangle and red rectangle have a vector representing their position, people talk about direction of a vector, but what direction are these vectors going in? they are static right? so that means they aren't going in any direction? or... is their direction relative to the origin (0,0)?

By definition, the origin is zero, but you can make "zero" mean anything you want. (0, 0) can mean the top-left corner of the screen, or the center, or anything else. As long as your values and operations are consistent, it doesn't matter what "zero" refers to.
Does this answer your other question?


for example let's say you have a checkpoint let's be vague and assume there is only one checkpoint in the game. The checkpoint is at (200,200) pixels on the screen, can we consider this checkpoint as the origin?

I think so, so this is correct ^^


people talk about direction of a vector, but what direction are these vectors going in? they are static right?

You're conflating two different things:
- A vector to represent the rectangle's position
- A vector to represent the rectangle's velocity
These are two different, independent things.

is their direction relative to the origin
Yes. The magnitude & direction notation of a vector is just another way of specifying it. It gives the same information as the <x, y> notation, just in a different form.

For example, if you have a vector in <magnitude, direction> notation, it might be <3, Pi/4>, where 3 is the magnitude, and Pi/4 is the angle from the x-axis. This is the same as saying, in <x, y> form,
that <x = 3*cos(Pi/4), y = 3*sin(Pi/4)>, or <3*sqrt(2)/2, 3*sqrt(2)/2>.
Last edited on
You're conflating two different things:
- A vector to represent the rectangle's position
- A vector to represent the rectangle's velocity
These are two different, independent things.

is their direction relative to the origin
Yes. The magnitude & direction notation of a vector is just another way of specifying it. It gives the same information as the <x, y> notation, just in a different form.


ah ok, so I think I'm over complicating the topic, as I mentioned in the start of the post a vector can represent different things such as a position or a vector, they are both vectors but have different meanings or contexts. And yes that also makes sense so both notations will represent the same position on the screen,

one thing I think I was confusing was magnitude and velocity, so let's say we have a velocity vector moving upward (x = 0, y = -10) and we apply that ( vector addition ) to our objects positional vector, our object will move upwards 10 spaces, I thought the magnitude of the velocity vector would be -10 as it's moving at a rate of -10 on the y axis,

one thing that still does kind of confuse me though is, why does magnitude represent x and why does direction represent y, isn't the x axis also technically direction?
Last edited on
See: https://www.youtube.com/watch?v=JTkNAXg4Vtc

You have the position vectors for both rectangles, equivalent to rA and rB in the video.
The distance between the two is equivalent to the magnitude of rAB in the video.

QED

Last edited on
Pages: 12