How do I proportionally position a sprite?

Get help using Construct 2

Post » Mon Feb 23, 2015 5:56 am

I want to position a bar on the screen based on the mouse x percentage across the screen. The pictures below demonstrate what I'm trying to achieve. I don't want the code or a capx - just the maths behind it :)

Grey box is the layout. Salmon box is the bar to be positioned.

Image

Image

As always, any help is much appreciated.
Thanks for reading.

-Crypt

[EDIT]

So far I have...
Code: Select all
Mouse.X / Layout.Width * 100

- gives a number between 1 and 100 which is the percentage of screen width at the mouse x coordinate.
Image
B
14
S
3
G
1
Posts: 61
Reputation: 1,003

Post » Mon Feb 23, 2015 6:10 am

Well you first can calculate the percentage of mouse.x across the screen with:
percent = mouse.x / screen.width

When percent= 0 you want bar.x = 0
and when percent = 1 you want bar.x = screen.width - bar.width

This is assuming there is no scrolling going on and the origin of the bar object is on the left.

You then can use lerp to set it up:
bar.x = lerp(0, screen.width - bar.width, mouse.x / screen.width)

You may also want to clamp the percent value so it stays in the range of 0 to 1 like so:
bar.x = lerp(0, screen.width - bar.width, clamp(mouse.x / screen.width, 0, 1))
B
92
S
32
G
107
Posts: 5,280
Reputation: 69,971

Post » Mon Feb 23, 2015 6:27 am

Clamp and Lerp are new to me. Thank you!

Trying it out right now...
Image
B
14
S
3
G
1
Posts: 61
Reputation: 1,003

Post » Mon Feb 23, 2015 9:29 am

I found lerp in the manual, but I have no idea how it works but it works beautifully and is super neat - far less complicated than I expected the formula to be. I'm going to assume that 'lerp' just deals with the complexities behind the scenes and I'm not gonna fuss over how it gets there.

Clamp - I cannot find in the manual - I'm guessing it works in a similar way to int().

Thanks for your quick reply @R0J0hound.
Image
B
14
S
3
G
1
Posts: 61
Reputation: 1,003

Post » Mon Feb 23, 2015 9:54 am

Lerp (a, b, t) as an equation is:
a+t*(b-a)

Clamp(a,b,c)
Just takes a value "a" and limits its value to between b and c
This is all that clamp does:
If a<b set a to b
If a>c set a to c
B
92
S
32
G
107
Posts: 5,280
Reputation: 69,971


Return to How do I....?

Who is online

Users browsing this forum: Chris Chan and 28 guests