Monday, 8 April 2019

Driving a car

If you need to create a car videogame, the controls are always relative where the car point to, so you need a little of geometry and trigonometry to do a correct work, let's see an example.
Let's create a stack with the image of a car, call the image car:
In order to rotate it, you just need to use the angle property, but how to move when it's rotated?
Now add this code to the card:


on arrowkey puls      
   put the keysdown into temp2
   repeat for each item tItem in temp2
      switch tItem
         case "65362"
            put the angle of image "car" into temp         
            #creaimo una strina del tipo x,y
            put -5 * sin( pi / 180 * temp) into movimento
            put "," after movimento
            put -5 * cos( pi / 180 * temp) after movimento
            move image "car" relative movimento      
            break         
         case "65364"
            #dobbiamo muoverla in indietro rispetto al verso del muso
            #prendiamo l'angolo della direzione
            put the angle of image "car" into temp         
            #creaimo una strina del tipo x,y
            put 5 * sin( pi / 180 * temp) into movimento
            put "," after movimento
            put 5 * cos( pi / 180 * temp) after movimento
            move image "car" relative movimento      
            break         
         case "65361"
            put the angle of image "car" into temp
            add 1 to temp
            set the angle of image "car" to temp
            break               
         case "65363"
            put the angle of image "car" into temp
            add -1 to temp      
            set the angle of image "car" to temp
            break                        
      end switch
   end repeat
end arrowkey


Finished! Explanation:
First of all, the angle property is always between 0 and 360, if you put the value out of this, livecode reconvert it, i.e. 361 becomes 1.
The same for position values, livecode convert to the nearest integer.
Just to keep in mind that angle is in degree, but sine and cosine use radians, so there is the conversion formula n/180.
The keydown is better for contemporary buttons pressed.
Finally, these are the coordinate systems on computers:
  • origin in the top left
  • X to the right
  • Y to the bottom
  • image angle at 12.00 and clockwise
like this:

No comments:

Post a Comment