Pages

Thursday, October 8, 2009

Drawing arrow in OpenGL

We have two points A and B in 3D. The problem is to find the way to draw a line that the started point is A and the later is B. We also want to have a little arrow at B.

One guy posted the guide in gamedev.net
Say: A = [x1, y1, z1] (start)
and B = [x2, y2, z2] (end)
and C = [x3, y3, z3] (arrow tip at one side)
and D = [x4, y4, z4] (tip at the other side)

if((z1-z2) != 0) {
first we make a normal vector:
x3 = 1
y3 = 1
z3 = (-(x1-x2)-(y1-y2))/(z1-z2)

adjusting the distance from the arrow axis to one fourth of the arrows lenght:
adj = sqrt((x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2)) / (4 * sqrt((x3^2)+(y3^2)+(z3^2)));
x3 *= adj
y3 *= adj
z3 *= adj

setting the other side:
x4 = -x3
y4 = -y3
z4 = -z3

gettin the point:
x3 = x1 + (3/4)*(x1-x2) + x3
y3 = y1 + (3/4)*(y1-y2) + y3
z3 = z1 + (3/4)*(z1-z2) + z3

x4 = x1 + (3/4)*(x1-x2) + x4
y4 = y1 + (3/4)*(y1-y2) + y4
z4 = z1 + (3/4)*(z1-z2) + z4
}

OK, I didn't double check this, but the clue is the "first we make a normal vector:" -section, the rest is fairly straight out. Oh and if you use float or double values, they rarely become zero, but if (z1-z2) should happen to be zero, then find the normal setting z3 = 1, y3 = 1, and x3 = (-(y1-y2)-(z1-z2))/(x1-x2), that should work work as well, and if (x1-x2) also is zero, just base it on y the same way.
Well, as I said, I didn't double check this, but I know it works, there might be simpler ways also, be sure to tell me if I made some stupid mistakes here.


I appreciate this explanation.

1 comment:

  1. http://www.codeproject.com/KB/GDI/arrows.aspx
    http://www.codeproject.com/KB/GDI-plus/ArrowRenderer.aspx
    http://kapo-cpp.blogspot.com/2008/10/drawing-arrows-with-cairo.html

    ReplyDelete