Created
          June 24, 2020 09:31 
        
      - 
      
 - 
        
Save photonstorm/385b57dde02efef3276111df71d974be to your computer and use it in GitHub Desktop.  
    Car follow path + boost
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | var config = { | |
| type: Phaser.AUTO, | |
| width: 800, | |
| height: 600, | |
| backgroundColor: '#2d2d2d', | |
| parent: 'phaser-example', | |
| scene: { | |
| preload: preload, | |
| create: create, | |
| update: update | |
| } | |
| }; | |
| var game = new Phaser.Game(config); | |
| var car; | |
| var path; | |
| var speed = 0.002; | |
| var pathDelta = 0; | |
| var prevPos = new Phaser.Math.Vector2(); | |
| function preload () | |
| { | |
| this.load.image('car', 'assets/sprites/car-yellow.png'); | |
| } | |
| function create () | |
| { | |
| var points = []; | |
| points.push(new Phaser.Math.Vector2(50, 200)); | |
| points.push(new Phaser.Math.Vector2(200, 100)); | |
| points.push(new Phaser.Math.Vector2(500, 50)); | |
| points.push(new Phaser.Math.Vector2(700, 300)); | |
| points.push(new Phaser.Math.Vector2(500, 500)); | |
| points.push(new Phaser.Math.Vector2(300, 400)); | |
| points.push(new Phaser.Math.Vector2(100, 300)); | |
| points.push(new Phaser.Math.Vector2(50, 200)); | |
| path = new Phaser.Curves.Spline(points); | |
| var graphics = this.add.graphics(); | |
| graphics.lineStyle(1, 0xffffff, 1); | |
| path.draw(graphics, 64); | |
| graphics.fillStyle(0x00ff00, 1); | |
| for (var i = 0; i < points.length; i++) | |
| { | |
| graphics.fillCircle(points[i].x, points[i].y, 4); | |
| } | |
| var start = path.getStartPoint(); | |
| car = this.add.sprite(start.x, start.y, 'car'); | |
| var boost = false; | |
| this.input.on('pointerdown', function () | |
| { | |
| if (!boost) | |
| { | |
| console.log('turbo boost'); | |
| boost = true; | |
| var maxSpeed = 0.006; | |
| this.tweens.addCounter({ | |
| from: speed, | |
| to: maxSpeed, | |
| ease: 'Sine.inOut', | |
| duration: 1000, | |
| hold: 1000, | |
| yoyo: true, | |
| onUpdate: function (tween) | |
| { | |
| speed = tween.getValue() | |
| }, | |
| onComplete: function () | |
| { | |
| console.log('boost off'); | |
| boost = false; | |
| } | |
| }); | |
| } | |
| }, this); | |
| } | |
| function update () | |
| { | |
| prevPos.set(car.x, car.y); | |
| var pos = path.getPoint(pathDelta); | |
| var speedX = pos.x - prevPos.x; | |
| var speedY = pos.y - prevPos.y; | |
| car.setPosition(pos.x, pos.y); | |
| car.rotation = Math.atan2(speedY, speedX); | |
| pathDelta = Phaser.Math.Wrap(pathDelta + speed, 0, 1); | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment