[SOLVED] Drag Back To Make A Ball Fling Into Air

Basically, I want to make it so that the more you drag back on a ball, the more the power increases until the the mouse button or finger is released. Once released, the ball will fling up with the power. I also want it to change directions when the player moves their finger left or right, or when the mouse is moved left or right. For example, if the finger moves a bit to the right when pulling back, the ball will fling a bit to the left. (Same with the mouse). So now I want to know how I would code this. How can I implement such feature in a game? I’m assuming it’s something to do with the screenToWorld feature.

Hi @DevPlex01,

One way to do the drag to build power thing is to get the start and end position of your mouse click and calculate the difference in one axis. For example:

MyScript.prototype.initialize = function() {
    this.startPos = new pc.Vec2();
    this.lastPos = new pc.Vec2(); 

    this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.onMouseDown, this);        
    this.app.mouse.on(pc.EVENT_MOUSEUP, this.onMouseUp, this);

MyScript.prototype.onMouseDown= function() {
   this.startPos.set(event.x, event.y);

MyScript.prototype.onMouseUp= function() {
   this.lastPos.set(event.x, event.y);

   var amountDraggedOnY = Math.abs(this.lastPos.y - this.startPos.y);

   // you can now use amountDraggedOnY to calculate a force

In the same way you can find the difference the player moved on the X axis, for example, and rotate/change dir.


To add on top of what @Leonidas has suggested, if you have a need to know the intermediate result of your swipe. For example, you have some sort of visual power indication, like a line stripe that fills the more power you have, or more particles shoot from your ball, etc. In this case, you can start recording the power in a variable on mousedown, add amountDraggedOnY to it on mousemove, and stop recording / reset it on mouseup. This way you will have a power value that you can visually show to the player.


Hello, I am trying to make a game and I’m trying to achive the same thing. Drag back to draw a line aim and shoot.

    var start = new pc.Vec3(this.startPos.x, this.startPos.y, 1);
    var end = new pc.Vec3(event.x, event.y, 1);
    var color = new pc.Color(1, 0, 1);
    var worldLayer = this.app.scene.layers.getLayerById(pc.LAYERID_SKYBOX);
    this.app.renderLine(start, end, color, {
        layer: worldLayer

I am using this code but it doesn’t create any lines.