I need help with some maths

Started by
12 comments, last by alvaro 9 years, 4 months ago

As I already said, I am young and I never studied vectors, I have no idea what normalization is.

Normalization is a process where you take a vector different than zero and create another vector that has the same direction but has a length of 1.

Let v = (x,y) be any vector different than (0,0).

length(v) = sqrt(x2+y2)

Now, define w = v/length(v) = (x/sqrt(x2+y2), y/sqrt(x2+y2))

If you want the length of "w" then:

length(w) = sqrt( ((x/sqrt(x2+y2))2 + (y/sqrt(x2+y2))2 )

length(w) = sqrt( x2/(x2 + y2) + y2/(x2 + y2))

length(w) = sqrt( (x2+y2)/(x2+y2) )

length(w) = sqrt(1)

length(w) = 1

One of the advantages of normalizing a vector is that when you multiply a vector of length 1 by a single value, that value becomes the length of the new vector.

So, if length(w) = 1 and you define z = r * w (r a single value, not a vector), then length(z) = r.

Another thing that's usually done in algebra is using the equations around the origin, not a random point, so it's easier to move the reference of your problem to the origin, solve the problem, and translate the solution back to the point you want.

All this is usefull for your problem.

First, translating the problem, you what a point that's at a distance of "r" from "p", so you can translate the whole problem to the origin by substracting "p". Your point "t" becomes "t-p" in this case.

Second, you use the normalization to make a vector of length 1 form the origin to "t-p", then multiply it by "r" to get a point in the circle of radius "r". That point is the solution around the origin, so you add "p" to it to move the solution back to your original "p" point.

Advertisement

m_clickPos.x = m_startPos.x + r * Normalize(m_clickPos - m_startPos).x;

m_clickPos.y = m_startPos.y + r * Normalize(m_clickPos - m_startPos).y;

There's your problem, in the first line you change the value of m_clickPos.x, so in the second line (m_clickPos - m_startPos) is not the same vector as the one in the first line.

Change that to:


Vector2 normalized = Normalize(m_clickPos - m_startPos);
m_clickPos.x = m_startPos.x + r * normalized .x;
m_clickPos.y = m_startPos.y + r * normalized .y;

Indeed that was the error, thank you everybody, it works !

Over the years I have developed a programming style that doesn't allow for this type of mistake. Most of my "variables" are not variable at all: They are initialized with some value computed when they are created and they are never modified. So if `m_clickPos' is the point t in your diagram, you need a different name for the point X in your diagram. Not only would this mistake be impossible, but your code would be more understandable.

This topic is closed to new replies.

Advertisement