How do I proportionally position a sprite?

  • 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.

    As always, any help is much appreciated.

    Thanks for reading.

    -Crypt

    [EDIT]

    So far I have...

    Mouse.X / Layout.Width * 100[/code:1gycr2d6]
    [ul]
    	[li]gives a number between 1 and 100 which is the percentage of screen width at the mouse x coordinate.[/li]
    [/ul]
  • 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))

  • Clamp and Lerp are new to me. Thank you!

    Trying it out right now...

  • 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

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • 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

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)