[Pharo-users] Calculate angle between two vectors (probably @Igor :)
Alain Busser
alain.busser at gmail.com
Mon Mar 17 01:51:45 EDT 2014
First of all, you could simplify your code with dotProduct, writing
dot2 := p1 dotProduct: p2.
But maybe you just need
((p1 normalized) dotProduct: (p2 normalized)) arcCos ;-)
You can also explore the polar coordinates...
Alain
On Sun, Mar 16, 2014 at 8:01 PM, MartinW <wm at fastmail.fm> wrote:
> Hello,
> i probably made some embarassing mistake, but as i cannot find it, i ask
> you
> to have a look at this method.
> It should calculate the angle between two vectors. And vectors are
> instances
> of Point (perhaps here is already a misconception?).
> It is used in my flocking simulation PharoBoids
> (http://smalltalkhub.com/#!/~MartinWalk/Boids)
>
> Here is my version of the method:
>
> angleBetween: vector1 and: vector2 onError: aBlock
> | cosinusOfAngle innerProductOfVectors productOfVectorsLengths|
> innerProductOfVectors := (vector1 dotProduct: vector2).
> productOfVectorsLengths := (vector1 r) * (vector2 r).
> productOfVectorsLengths = 0 ifTrue: [ ^ aBlock value ].
> cosinusOfAngle := innerProductOfVectors / productOfVectorsLengths.
> ^ cosinusOfAngle arcCos
>
> But my Boids behave wrong when i use it. I found another implementation of
> the same problem by Igor Stasenko which works and looks like this:
>
> angleBetween: p1 and: p2 ifDegenerate: aBlock
> " Calculate an angle (in radians) between two vectors.
> Evaluate a block, in case if calculation not possible because one of the
> vectors has zero length "
>
> | x1 y1 x2 y2 dot2 n2 |
> x1 := p1 x.
> y1 := p1 y.
> x2 := p2 x.
> y2 := p2 y.
>
> dot2 := x1 * x2 + (y1 * y2).
> dot2 := dot2 * dot2.
>
> n2 := (x1*x1 + (y1*y1)) * (x2*x2 + (y2*y2)).
>
> n2 = 0 ifTrue: [ ^ aBlock value ].
>
> ^ (dot2 / n2) arcCos
>
> Can anybody explain the problem of my method? M.
>
>
>
> --
> View this message in context:
> http://forum.world.st/Calculate-angle-between-two-vectors-probably-Igor-tp4749351.html
> Sent from the Pharo Smalltalk Users mailing list archive at Nabble.com.
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.pharo.org/pipermail/pharo-users_lists.pharo.org/attachments/20140317/8099a1d0/attachment.html>
More information about the Pharo-users
mailing list