News:

Don't forget to visit the main site! There's lots of helpful docs, patches, and more!

Main Menu

[65816] SQRT subroutine [solved]

Started by JAM, March 09, 2012, 12:45:27 AM

Previous topic - Next topic

JAM

There are division, multiplication and even sin and cos subroutines (if I remebmer right) in Super Metroid. Is there an subroutine in SM ROM that can make square root from cetrain value? If not, can it be done using 65816 language? I just have no idea.

snarfblam

Why do you need to take a square root? Depending on what you are doing, you might be able to cheat a little bit, but if you google it, there are 65816 square root routines out there you can use.

JAM

#2
Quote from: snarfblam on March 09, 2012, 07:47:36 AM
Why do you need to take a square root?
To get movement per frame using this formula: √(x2+y2)

I think I've got it by myself. I'm posting it here in case if someone will need it.


STA $4204
LDX #$0000
Loop:
INX
SEP #$20
STX $4206
REP #$20 ;3
PHA ;3
NOP ;2
NOP ;2
PLA ;4 14 in total
CPX $4214
BNE Loop
LDX $4214
LDY $4216
RTS


Value is in A. Result is in X. Divide remainder is in Y.

EDIT: This one could also work, it is shorter. Haven't tested it.


STA $4204
LDX #$0000
Loop:
INX
STX $4206
PHA ;3
PLA ;4
PHA ;3
PLA ;4 14 in total
CPX $4214
BNE Loop
LDX $4214
LDY $4216
RTS

Drewseph

Sorry for bumping this, But this is such a useful routine and it comes with many questions.

Since most of this code is not commented, what exactly does it do?  When in the calculation do I plug this into?

I have a routine in place which gets samus' pixels traveled X and Y, and I know how to square them.  Do I plug this code in after I get them Squared and added together?

In this example which ram address is the sum of x2+y2 kept?

Crashtour99

Basically this is just using the hardware registers that are already set up to do division, so it's making use of what the game already has available.

If I understand it correctly, you should have the number you want the square root of in A (so x2+y2), and then just JSR to this routine.  When it gets done, you'll have your original number in A, and your square root result in X (whole number) and Y (remainder).

If you want to keep your previous values for x/y, it'd probably be a good idea to PHX/PHY before JSRing to this routine, or storing them in an empty RAM slot somewhere.