(Solved)Convert player.x into distance percentage.

Started by FanOfHumor, Fri 07/01/2022 00:15:41

Previous topic - Next topic

FanOfHumor

     Hi. I want to be able to detect the distance in pixels from the players position.If The player is at 300 it should set the integer to 100%.And if the player is at the end of the screen then the integer would equal zero no matter what edge the players at.In simple I need the script to consider 300 to be 100%.And continuously change from player.x .All I have as an example is this {percent=pixel-300;}and I know this doesn't work.This is a lost knowledge to me so anything will probably refresh my memory.Sorry I couldn't do a better topic name.
Thanks

arj0n

so you could let that be continuously re-calculated in rep_exec with something like 100/300*player.x, right?

FanOfHumor

#2
Thanks for helping me remember.

arj0n

#3
It is just the formula: 100% divided by max distant (which is 300) times current player-position.

Create a global int, and name it percent for example and set its default value to 0.

Then in the global script (or in the room script if the distance percentage calculation is only needed in one specific room) use something like in the rep_exec section:

percent = 100/300*player.x;

Now the int percent will give you a value between 0 and 100

Edit:
After posting this answer I noticed you editted your post, so my answer/info here might be obsolete now  (roll)

Crimson Wizard

#4
EDIT: well, looks like this was not necessary, but I'll leave my answer just in case someone has similar questions.

Do you need full 2D distance, or distance only along the X axis?

Full distance is calculated as
Code: ags

float dist = Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));

where x1,y1 are coordinates of one point and x2,y2 are coordinates of another.

If you need only distance along the axis, that's obviously
Code: ags

int dist = x2 - x1;


Converting a value to the percentage of something is done as
Code: ags

float percent = (value * 100.0) / full_value;

where the "full_value" is the value corresponding to 100%.


Important thing is that in AGS float and integer values do not covert automatically, but have to be converted using IntToFloat and FloatToInt.

So the final code may look like (in the full 2D distance case):
Code: ags

float x1 = IntToFloat(player.x);
float y1 = IntToFloat(player.y);
float x2 = other location's x
float y2 = other location's y
float dist = Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
float percent_f = (dist * 100.0) / 300.0;
int percent = FloatToInt(percent_f);

SMF spam blocked by CleanTalk