Applying force on a certain angle

Hi
I have a problem where I have an object in 2d Screen that I push back and needs to add force towards that direction on the 3d Object just like slingshot. Attaching image to explain my problem a bit .Can anyone help with that?
Thanks

You can get screen space position relative to your ball with this function.

Slingshot.prototype.getRelativeSSVector = function(e){
    var world_pos = this.ball.getPosition();
    var screen_pos = new pc.Vec3();
        
    this.entity.camera.worldToScreen(world_pos, screen_pos);
        
    var relative_screen_pos = new pc.Vec3(e.x, e.y, screen_pos.z);
    relative_screen_pos.sub(screen_pos);
    return relative_screen_pos;
};

Then you can simply just applie to force to your object on mouseup

Slingshot.prototype.mouseUp = function(e){
    var relative_pos = this.getRelativeSSVector(e);
    
    relative_pos.z = relative_pos.y;
    relative_pos.y = 0;
    relative_pos.mulScalar(-1); //Inverse the momentum
    
    this.ball.rigidbody.applyForce(relative_pos);
};

Be aware we reverse z and y as screen space y is right, where world space z is right.

Example Project:
https://playcanvas.com/editor/scene/1250526

1 Like

It is working alright in the example project that you showed however it is not working in my project.
I have a football in the UI screen as you can see and when I end mouse click, the ball goes in the same direction no matter if the UI’s football is right or left.
Can you tell me what is going on here?

Here is the scene where I am trying to replicate what is happening in my original project and even this is better than my project but we can observe its not working perfectly here.
https://playcanvas.com/editor/scene/1250752

I think its becouse you have the camera at an angle, the code I wrote assumes you have a top down camera. You can do a raycast to the plane instead of the cheep getRelativeSSVector i wrote

http://developer.playcanvas.com.s3-website-eu-west-1.amazonaws.com/ru/tutorials/entity-picking/