Home > front end >  Phaser 3: Draw a live curve
Phaser 3: Draw a live curve

Time:05-22

I am following the post:

https://cedarcantab.wixsite.com/website-1/post/phaser-coding-tips1-2-revisited-part-1-creating-a-game-like-tanks---worms

And I am trying to draw a live curve that determines where the bullet overlaps the land before shooting. Does anyone have any ideas for this situation? Thank you.

CodePudding user response:

A solution without too much calculations could be, use a dummy object as a "tracer bullet".
With other Words, make a physics object, that doesn't collide with anything, "shoot" that object, and draw, in a specific interval a small "marker", that would traces the arc / path taken.

Here is a small demo, showcasing this idea:

var config = {
    type: Phaser.AUTO,
    width: 536,
    height: 183,
    scene: {
        create,
        update
    },
    physics:{
      default:'arcade', 
      arcade:{
        gravity:{y: 260},
      }},
    banner: false
}; 

let player;
let firstMarker;
let pathItems;
let lastMarker;

function create () {
    this.add.text(10, 10, 'move mouse for targeting\nhold still to see the full path.', {color:'#ffffff'})
    let floor = this.add.rectangle(0 , 183, 535, 20, 0x00ff00).setOrigin(0, .5);
    pathItems = this.add.group();
    player = this.add.rectangle(30 , 158, 30, 30, 0x1AA840);
    player.setDepth(2)
    
    firstMarker = this.add.arc(-10, 0, 5, 0, 2 * Math.PI, true, 0xffffff);
    
    this.physics.add.existing(firstMarker);
    
    this.input.on('pointermove', function (pointer) {
        startMarkerTrail(this, player, pointer)
    },this);
}

function update(time, delta){

    let {x, y} = firstMarker
    if(!lastMarker || Phaser.Math.Distance.Between(x, y, lastMarker.x, lastMarker.y ) > 20){
      let marker = this.add.arc(x, y, 3, 0, 2 * Math.PI, true, 0xcdcdcd);
      pathItems.add(marker);
      lastMarker = {x, y};
  }
}

function startMarkerTrail(sccene, player, pointer){
    let speed = 300;
    let angle = Phaser.Math.Angle.BetweenPoints(player, pointer);
  
    pathItems.clear(true);
    firstMarker.setPosition( player.x, player.y );
    sccene.physics.velocityFromRotation(angle, speed, firstMarker.body.velocity);
   
}

new Phaser.Game(config);
* {padding:0;margin:0;}
<script src="//cdn.jsdelivr.net/npm/[email protected]/dist/phaser.js"></script>

If you need a line can make the distance smaller and/or the size of the markerpoints smaller.

  • Related