Jump to content
IGNORED

How to quickly calculate direction of vector


vdub_bobby

Recommended Posts

If an object has it's overall velocity described by X-velocity and Y-velocity, is there a quick-n-dirty way to get the direction of the overall velocity? I.e., I want the direction of the vector, I don't care about the magnitude.

 

I just need a really rough estimate; within ~30 degrees.

 

I can take the arctan of Vy/Vx, but that involves division...

Link to comment
Share on other sites

Depending on the magnitude of the X and Y velocities, the fastest method is probably a look-up table. For instance, if your velocity is +/-7 in each direction, you can simply shift one of the axis 4 bits, and OR the other vector. Then use a 256 byte (precalculated) look-up table.

lda dx
asl a
asl a
asl a
asl a
ora dy
tax
lda angle,x

 

Note: It should be possible to still use a 256 byte look-up table with velocities up to 15, taking advantage of reflection.

Link to comment
Share on other sites

I just need a really rough estimate; within ~30 degrees.

 

Getting it to a quadrant is easy. An octant isn't much harder, though you might want to scale X and Y first (x*5 and y*3 for best accuracy at 1x resolution, though you could use x*1 and y*2).

 

Your next subdivision could be done reasonably accurately by seeing whether the larger value was more or less than twice as big as the smaller. That would divide the circle into 16 parts. They wouldn't all be 22.5 degrees, unfortunately--they'd be 26.6 and 18.4 degrees, but that may be good enough, especially given the simplicity.

 

Maybe do something like:

; Assumes dx and dy are usable as scratchpad
 lda dx
 cmp #128
 ror temp
 bpl nonegdx
 eor #255
 sta dx
nonegdx:
 lda dy
 cmp #128
 ror temp
 bpl nonegdy
 eor #255
 sta dy
nonegdy:
 lda dx
 cmp dy ; carry if dx >= dy
 ror temp
 bmi noswap; branch if dx >= dy
 ldx dy
 sta dy
 stx dx ; Now dx >= dy
noswap:
 lda dx
 lsr
 cmp dy
 ror temp
; The top four bits of temp now define one of 16 directions (not in order).
; Shift right four bits and do a table lookup.

Edited by supercat
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...