Moving a sprite from one point to another via a percentage.

0 favourites
  • 5 posts
From the Asset Store
Connect the dots in the correct order and draw happy animals!
  • Hi all, hopefully you can help me with this.

    I have a sprite (A) that I want to move between two X positions on the layout (B, the starting point and C, the ending point).

    That's easy enough to do with lerp, however, I have a global variable that I want to tie into these two positions.

    When I press a key I want to add a number to that global variable, say 20 for example and have the sprite, A, move SMOOTHLY 20% of the way between points B and C.

    Basically I want B to be 0% and C to be 100% but I'm not sure how to write that expression wise.

    Any thoughts?

    Thanks for any help :)

  • Try Construct 3

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

    Try Now Construct 3 users don't see these ads
  • Let's say you have progress variable, changing from 0 to 1. When you press a key, you add 0.2 to progress and calculate the destination point:

    On any key pressed:
     Add 0.2 to progress 
     Set destinationX to lerp(B.x, C.x, progress)
    

    Then you can move your A sprite to this destination point using some behavior like MoveTo, or with another lerp:

    On every tick: 
     A set X to lerp(A.x, destinationX, dt)
    
  • That was ridiculously helpful! Thanks so much, works like a charm.

  • So this works very well but I've come across an issue with it while testing.

    When I go to add a number to the variable, 0.2 for example Construct will occasionally add a whole mess of numbers after it. So instead of adding 0.2 it will add 0.29999999999999999999 or something like that.

    This screws everything up as I'm relying on these values to be perfectly precise as other functions in the project depend on it to be that way.

    It doesn't happen every time, but it happens enough that it's a problem.

    Any 'hopefully' simple fix for this?

  • Decimal numbers are seldom perfectly precise on computers. For example 0.2 can’t be precisely represented in floating point numbers so it will be a bit off which adds up with calculations. It’s not really that far off actually if you look at it.

    Anyways this is seldom an issue unless you’re displaying the numbers, because by default too many decimal places are displayed.

    A solution is to round the number before displaying it.

    Set var to round(var*10)/10

    Or maybe after every time you do a calculation, or before you want to compare a number to be an exact decimal number.

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