Search code examples
javascripttypescriptgame-physicsphaser-framework

Cannon Fire Phaser3


I want to make cannon fire for my game I developed in 2D phaser3. I haven't achieved this move yet. When I code it this way, it falls directly down sharply after a certain point. How can I get the Cannon Fire shot here.

import {
  ActorProps,
  ICollectable,
  IDieable,
  IMoveable,
} from "@games/common/interfaces";
import { Actor } from "@games/common/objects";

export default class Cannon
  extends Actor
  implements IMoveable, IDieable, ICollectable
{
  declare body: Phaser.Physics.Arcade.Body;

  private initialX: number;
  private initialY: number;
  private velocityX: number;
  private velocityY: number;
  private isMoving: boolean;
  private isMovingUp: boolean;

  constructor(props: ActorProps) {
    super(props);
    this.scene.physics.add.existing(this);
    this.body.setAllowGravity(false);

    this.initialX = this.x;
    this.initialY = this.y;
    this.velocityX = 100;
    this.velocityY = -100;
    this.isMoving = true;
    this.isMovingUp = true;
  }

  update(time: number, delta: number): void {
    if (this.isMoving) {
      this.x -= this.velocityX * (delta / 1000);
      this.y += this.velocityY * (delta / 2000) * 0.5;

      if (this.x >= this.initialX + 200 || this.y <= this.initialY - 200) {
        this.velocityY = -this.velocityY;
      }

      if (this.velocityY < 0 && this.y >= this.initialY) {
        this.isMoving = false;
        this.y = this.initialY;
      }
    }
  }

  die(): void {}

  move(): void {}

  collect(...props: any[]): void {}
}

Currently the object is accelerating up and to the left from the starting position, but I cannot get the result I want because it moves according to fixed values.

I made this code in unity and it works correctly. I used the parabola formula.

public float a=-1, b=0, c=0;
    
    public float x=-5;
    [Range(0,10)]public float speed;
    // Update is called once per frame
    void Update()
    {
        Vector3 newPos = new Vector3(x,axx+bx+c,0);
        transform.position = newPos;
        x += Time.deltaTime speed;
    }

Solution

  • The main issue is, that you are not using the phyiscs engine.
    you shouldn't set x and y properties yourself, you should let the engine do this for you. With the function setVelocity (link to the documentation), or set the acceleration with setAcceleration (link to the documentation).

    But to use those functions you woould have to rewrite some of your code.

    Checkout these offical examples/demos (basic platformer, mini spaceship, acrade physics example collection ) for details how to use the arcade engine in phaser.