We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I quickly threw together my version of a popular mobile game called "Sine Line".
Links to my code (whichever you prefer): https://pastebin.com/FfxhJs6s https://hastebin.com/jekezecawu.js
The code seems to work fine on both PC and Mobile. But, I think it slowed down considerably after I added the Collision checking (Line 59) in my draw loop, especially on mobile.
Here's a link for quick testing: http://random-codes.000webhostapp.com/sineline.html
I'd like to optimize it further as I do think there's room for it, but I can't seem to find any way. Any help would be appreciated :')
Answers
It looks okay to me. One thing that you might consider doing is pre-calculating some values that you commonly reuse. For example, you do this:
But you could do this:
Not sure if that'll help even... but worth a shot, eh?
Do you have a means to remove old blocks when they left the screen?
Alternatively give them a new position so they appear again (instead of making new ones)
yes, I am removing the blocks once they leave the screen.
I'll try the suggestions given.
@Tushar - first things first: set up some way to properly measure performance. E.g. something that displays a framerate (actually even that is fairly crude) so you can make a more objective decision on whether your 'optimisation' is actually effective ;)
Then here are some things to try:
Cache calculated values where possible
As TfGuy44 said, avoid repeating calculations - store these as soon as possible:
For example anything referencing fractions of
width
orheight
can be calculated and stored in setup() (just make sure you use a variable that's available in draw) - e.g.It also used to be the case that you should set variables used in loops outside the loop - e.g.:
avoid iterating over the same loop multiple times
You could combine move/update and show methods and get:
Avoid expensive array operations
splice()
is a relatively slow array operation. If you splice an element from an array that you're also pushing new objects to; then you should consider fixing the size of the array to the maximum number of objects you'll require and just hide unused elements from view when they're not needed. You should definitely be able to re-cycle your trails objects and probably the blocks too...For a technical perspective see this
BTW - I haven't run your code - so maybe this is deliberate - but your collision detection appears to only check one block (
block[0]
) for a hit. If the arrow can hit any of the visible blocks then you need to do that check in a loop (which could slow things down even more)If things start getting really laggy then you might want to use time-based animation: that allows you to essentially drop frames so the animation always runs at the same speed.