# Creating a Bullet effect (based on a Unity example)

**URL:** <https://forum.babylonjs.com/t/creating-a-bullet-effect-based-on-a-unity-example/58351>\
**Category:** Tutorials and tips\
**Tags:** tutorial, bullet, unity\
**Created:** [May 10, 2025, 4:07pm UTC](https://forum.babylonjs.com/t/creating-a-bullet-effect-based-on-a-unity-example/58351 "2025-05-10T16:07:09Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![TiagoSilvaPereira](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/tiagosilvapereira/32/25835_2.png) [@TiagoSilvaPereira](https://forum.babylonjs.com/u/TiagoSilvaPereira)\
**Post date:** [May 10, 2025, 4:07pm UTC](https://forum.babylonjs.com/t/creating-a-bullet-effect-based-on-a-unity-example/58351/1 "2025-05-10T16:07:09Z")

</div>

Hello everyone, how are you? I hope you are all doing great.

I’ve recently been thinking about how to make a reusable bullet code with BabylonJS for the game I’m developing to publish on Steam:

> [@I'm making a Game for Steam (I hope) with BabylonJS](https://forum.babylonjs.com/t/im-making-a-game-for-steam-i-hope-with-babylonjs/56565):
>
> Hello everyone, I hope you are all well! I am happy to share this small game prototype that I have been working on for a few weeks using BabylonJS. My idea is to publish it on Steam, mainly to better understand how the platform works (and maybe, publish more games in the future). The game is very simple; it is a City Builder + minimalist strategy, the objective of which is to progress until you manage to create a city with 100,000 inhabitants. I would be …

I watched an exciting Unity tutorial and decided to implement something similar with BabylonJS.

[![](https://img.youtube.com/vi/oqidgRQAMB8/hqdefault.jpg "How to make a Tower Defense Game (E05 SHOOTING) - Unity Tutorial") ](https://www.youtube.com/watch?v=oqidgRQAMB8)

Ultimately, I got a code very close to the Unity version, which works well (and it doesn’t need collision detection, which I think is good for performance). I want to share the code with you:

```ts
import Engine from "../core/Engine"
import type MainScene from "../scenes/MainScene"
import { Space, TransformNode, type InstancedMesh, type Vector3 } from "@babylonjs/core"

export class Bullet {
    protected scene: MainScene
    protected mesh: InstancedMesh
    protected transformNode: TransformNode

    protected target: Vector3 | null = null
    protected speed: number = 0.05
    
    protected onHit: (() => void) | null = null

    constructor(scene: MainScene, target: Vector3, position: Vector3) {
        this.scene = scene

        this.transformNode = new TransformNode("bulletTransform", this.scene.getScene())
        this.transformNode.position = position.clone()

        this.mesh = this.createMesh()

        this.seek(target)

        this.scene.getScene().onBeforeRenderObservable.add(() => {
            this.update()
        })
    }

    createMesh(): InstancedMesh {
        const mesh = this.scene.bulletMesh?.createInstance(`bullet`) as InstancedMesh

        mesh.setEnabled(true)
        mesh.parent = this.transformNode
        mesh.position.setAll(0)

        return mesh
    }

    seek(target: Vector3): void {
        this.target = target

        this.transformNode.lookAt(this.target)

        Engine.playAudio(this.getSound())
    }

    getSound(): string {
        return "gunSound"
    }

    setOnHit(callback: () => void): void {
        this.onHit = callback
    }

    update(): void {
        if(this.target === null) {
            this.destroy()
            return
        }

        const deltaTime = this.scene.getDeltaTime()

        const direction = this.target.subtract(this.transformNode.position)
        const distanceThisFrame = this.speed * deltaTime

        if(direction.length() < distanceThisFrame) {
            this.transformNode.position = this.target
            this.hitTarget()
            return
        }

        direction.normalize()
        this.transformNode.translate(direction, distanceThisFrame, Space.WORLD)
    }

    hitTarget(): void {
        if (this.onHit) {
            this.onHit()
        }

        this.destroy()
    }

    destroy(): void {
        this.target = null
        this.onHit = null
        
        this.mesh.dispose()
        this.transformNode.dispose()
    }
}

```

As you can see, it’s pretty simple to extend the class to create other types of shots:

```ts
import { Bullet } from "./Bullet"
import { type InstancedMesh } from "@babylonjs/core"

export class LaserShot extends Bullet {
    getSound(): string {
        return "laserShotSound"
    }

    createMesh(): InstancedMesh {
        const mesh = this.scene.laserShotMesh?.createInstance(`laserShot`) as InstancedMesh

        mesh.setEnabled(true)
        mesh.parent = this.transformNode
        mesh.position.setAll(0)

        return mesh
    }
}

```

And here is a simple example of its usage:

```ts
private async update(): Promise<void> {
    switch (this.state) {
       // ...

        case "ATTACKING":
            await this.attack()
            break
    } 
}

private async attack(): Promise<void> {
    // ...

    this.timeUntilFire += deltaTime
    if (this.timeUntilFire >= GameConfig.shipConfig.attackInterval) {
        this.timeUntilFire = 0
        await this.shoot()
    }
}

private async shoot(): Promise<void> {
    // ...

    const bullet = new Bullet(this.scene, this.target.getPosition(), this.model.position)
    bullet.setOnHit(() => {
        if (!this.target || !this.target.hasBuilding()) return
        this.target.building!.takeDamage(GameConfig.shipConfig.shootDamage)
    })

}

```

Hope this helps. Have a great weekend, everyone!

**EDIT:** added an example based on @labris base code:

> **[Babylon.js Playground](https://playground.babylonjs.com/#WROYL5%234)**
>
> Babylon.js playground is a live editor for Babylon.js WebGL and WebGPU 3D scenes

---

<div class="post-metadata">

**Author:** ![Dad72](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/dad72/32/13_2.png) [@Dad72](https://forum.babylonjs.com/u/Dad72)\
**Post date:** [May 10, 2025, 6:39pm UTC](https://forum.babylonjs.com/t/creating-a-bullet-effect-based-on-a-unity-example/58351/2 "2025-05-10T18:39:15Z")

</div>

Thanks for sharing.  
A demo on the playground would be cool for see the result.

---

<div class="post-metadata">

**Author:** ![labris](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/labris/32/12576_2.png) [@labris](https://forum.babylonjs.com/u/labris)\
**Post date:** [May 10, 2025, 7:30pm UTC](https://forum.babylonjs.com/t/creating-a-bullet-effect-based-on-a-unity-example/58351/3 "2025-05-10T19:30:25Z")

</div>

I put the class into PG - [https://playground.babylonjs.com/#WROYL5#2](https://playground.babylonjs.com/#WROYL5#2)  
But it is not easy to understand how it should work 🙂

---

<div class="post-metadata">

**Author:** ![TiagoSilvaPereira](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/tiagosilvapereira/32/25835_2.png) [@TiagoSilvaPereira](https://forum.babylonjs.com/u/TiagoSilvaPereira)\
**Post date:** [May 12, 2025, 2:57pm UTC](https://forum.babylonjs.com/t/creating-a-bullet-effect-based-on-a-unity-example/58351/4 "2025-05-12T14:57:44Z")

</div>

@Dad72 @labris Whoops, my bad. I should have added a Playground 😊

@labris, Thanks for transferring the class to the Playground. I took the liberty of implementing the example using your code as a base 😁

The current code version does not use collision detection, since it is not necessary for the game I am developing. Still, changing the logic to use collision detection instead of target distance is not too difficult.

> **[Babylon.js Playground](https://playground.babylonjs.com/#WROYL5%234)**
>
> Babylon.js playground is a live editor for Babylon.js WebGL and WebGPU 3D scenes

Thanks and have a lovely week!
