Credit to @Albertos for the code.
changes I want to make:
Make it so I can set the rotation and position I want it to go to when I pick it up
Make it so if I just click the right mouse I drop the entity, but if I hold the right mouse I throw it forward.
Make it so I can press F to pick it up not the left mouse.
var PickerRaycast = pc.createScript('pickerRaycast');
// initialize code called once per entity
PickerRaycast.prototype.initialize = function() {
this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.onSelect, this);
this.on('destroy', function() {
this.app.mouse.off(pc.EVENT_MOUSEDOWN, this.onSelect, this);
}, this);
this.dragging = false;
this.pickedEntity = null;
this.raycastDistance = 5;
};
PickerRaycast.prototype.onSelect = function (event) {
// check if not already dragging
if (!this.dragging) {
// create raycast to check if there is an entity to drag
var screenCenterX = (this.app.graphicsDevice.width / 2) * this.app.graphicsDevice.maxPixelRatio;
var screenCenterY = (this.app.graphicsDevice.height / 2) * this.app.graphicsDevice.maxPixelRatio;
var start = this.entity.camera.screenToWorld(screenCenterX, screenCenterY, this.entity.camera.nearClip);
var end = this.entity.camera.screenToWorld(screenCenterX, screenCenterY, this.raycastDistance);
this.app.systems.rigidbody.raycastFirst(start, end, function (result) {
// check if entity is pickable
if (result.entity.tags.has('pickable')) {
// start dragging
this.dragging = true;
// get entity
this.pickedEntity = result.entity;
// get correct position and rotation to drag
var dragPosition = this.pickedEntity.getPosition();
var dragRotation = this.pickedEntity.getRotation();
// change rigidbody type to be able to drag
this.pickedEntity.rigidbody.type = 'kinematic';
// make entity part of player
this.pickedEntity.reparent(this.entity);
// apply correct position and rotation
this.pickedEntity.setPosition(dragPosition);
this.pickedEntity.setRotation(dragRotation);
}
}.bind(this));
}
// if already dragging prepare entity for release
else {
// get correct position and rotation to drop
var dropPosition = this.pickedEntity.getPosition();
var dropRotation = this.pickedEntity.getRotation();
// make entity part of world
this.pickedEntity.reparent(this.app.root.findByName('Root'));
// apply correct position and rotation
this.pickedEntity.setPosition(dropPosition);
this.pickedEntity.setRotation(dropRotation);
// change rigidbody type back to original
this.pickedEntity.rigidbody.type = 'dynamic';
// end dragging
this.dragging = false;
}
};