Reputation: 394
I'm using FlyControls.js
for my camera view
I'm trying to add a projectile
to my object
The projectile should use the angles from camera position, to crosshair/reticle position, and flow freely through 3D space
I've tried to use camera.position.angleTo(crosshair.position)
but it only returns a single float value. In 2D I'd use sin
and cos
, but 3D is different
Also, the projectile is a cylinder
, how would I rotate the cylinder to face the direction it's going?
//how to get this information?
projectile.angle = {
x: ?,
y: ?,
z: ?,
};
//how to get this information?
projectile.rotation = faceTowardsDestination;
function animate(){
//projectile movement
projectile.position.x += projectile.angle.x * projectile.speed;
projectile.position.y += projectile.angle.y * projectile.speed;
projectile.position.z += projectile.angle.z * projectile.speed;
requestAnimationFrame(animate);
}
Projectile (cylinder) should fire from spaceship, towards the crosshair point, and point towards it's destination
Upvotes: 0
Views: 602
Reputation: 28482
What you're searching for is the Object3D.lookAt(vec3)
method see here for docs. It rotates the object so it's directly "looking at" the position you tell it to.
// Establish the coordinages of the target
const target = new THREE.Vector3(x, y, z);
// Make the missile point directly at the position of your target
projectile.lookAt(target);
let speed = 1;
function animate() {
// Now you move it forward by translating down its own Z-axis
projectile.translateZ(speed);
requestAnimationFrame(animate);
}
When your projectile is already rotated to face the crosshairs, you only need to translate it down its local Z-axis (not the global z-axis), so no need to worry about setting the X & Y coordinates.
Upvotes: 2
Reputation: 348
In order for a projectile to go towards the crosshair, you first have to project the location of the crosshair far in front of the camera.
The simplest way I can suggest doing this is creating an infinite plane that's a child of child of the camera, placing it some distance away, and then casting a ray using a Raycaster
to find the intersection of the crosshair with this plane. See an example of intersection between the mouse pointer and a surface here.
The vector between your ship's position and this intersection is the direction of travel you'll want to use for your projective. You probably want to adjust the rotation of the ship accordingly.
Upvotes: 0