Finding opposite edge (wraparound) location given vector and location

47 Views Asked by At

A drawing of my current situation

I am making a game that has a wraparound effect for some objects. The objects re-spawn at the opposite 'point' of the screen that they exit. I need to find this opposite point $(x_2, y_2)$ only given $(x_1, x_2)$, the velocity $(v_1, v_2)$ and the 'window size' $w \text{ width } , h \text{ height }$. Some other examples have been drawn in different colors.

I do have a working implementation of this, but it only works in the horizontal direction. I'd like to extend it to work at any angle. I have tried using the unit vector but I'm not sure what calculations to perform on it.

2

There are 2 best solutions below

8
On

This can be done via modulo arithmetic:

$$x_2 = x_1 + tv_1 \pmod{w}$$

$$y_2 = y_1 + tv_2 \pmod{h}$$

0
On

It looks from your examples that you basically need to find the other point at which the line through $(x_1,y_1)$ with direction vector $(v_x,v_y)$ intersects the bounding box. Effectively, you are clipping the line against the box. You can find many algorithms for doing so, such as Cohen-Sutherland, Cyrus-Beck, &c. Here you know that one of the endpoints is already clipped to the box, so you can make some simplifications to these algorithms. For example, the Skala algorithm classifies the vertices of the bounding box against the equation $ax+by+c=0$ of the line, represented as a homogeneous vector, to determine which edge is crossed, after which computing the crossing point is straightforward. For your application, a vector that represents the line is $$\mathbf l = (v_x,v_y,0)\times(x_1,x_2,1) = (v_y,-v_x,v_xy_1-v_yx_1).$$ For each vertex $\mathbf p = (x_p,y_p,1)$ compute the sign of $\mathbf l\cdot\mathbf p = v_yx_p-v_xy_p+(v_xy_1-v_yx_1).$ (This is the left-hand side of the equation of the line evaluated at $\mathbf p$.) If any of these are zero, then the line passes through that vertex. If the signs for adjacent vertices differ, then the line intersects the edge with those endpoints. Of course, one of these crossings will be $(x_1,y_1)$ itself. If the other crossing is not at a vertex (in which case you’re done), it will cross exactly one of the other edges. For a horizontal edge of the form $y=y_e$, the $x$-coordinate of the intersection is easily found to be $x_1+{v_x\over v_y}(y_e-y_1)$. Similarly, for a vertical edge $x=x_e$, the intersection $y$-coordinate is $y_1+{v_y\over v_x}(x_e-x_1)$.