Enemy in Three.js advances menacingly towards the player

I'm working with three.js and I've got a spaceship located at coordinates xyz. I want it to fly towards a mesh object representing a planet at coordinates xyz.

I've been struggling to figure this out and it's been quite challenging.

The spaceship needs to move in a straight line, maintaining a constant speed towards the planet.

Answer №1

 updateFcts.push(function(delta, now){

    if (shipArr[0]===undefined){
}else{  

       //creating two vector instances
var xd = new THREE.Vector3(marsMesh.position.x,marsMesh.position.y,marsMesh.position.z);
var yd = new THREE.Vector3(shipArr[0].position.x,shipArr[0].position.y,shipArr[0].position.z);
//calculating the distance / hypotenuse to the xyz location
var dicks = shipArr[0].position.distanceTo(marsMesh.position);

 var subvec = new THREE.Vector3();
     subvec = subvec.subVectors(xd,yd);
     //subtracting the 3 vectors.
   var hypotenuse = dicks;
     console.log(hypotenuse);
   //limiting the distance to 1.5 from the target planet

       if(hypotenuse > 1.5){
        //console.log(hypotenuse);

    shipArr[0].position.y += .0001*200*(subvec.y/hypotenuse);
    shipArr[0].position.x += .0001*200*(subvec.x/hypotenuse);
    shipArr[0].position.z += .0001*200*(subvec.z/hypotenuse);
    }else{
    //within fire range
    alert ("FIIIIIRE");

    }


}

})

I experimented with tween.js but found it unsatisfactory, so I developed my own function.

Answer №2

If you're looking for a solution to animate objects in your web project, you may want to consider using the tween.js library available at https://github.com/sole/tween.js. This library is specifically designed for animation purposes.

For a simple demonstration, you can check out this example at http://jsfiddle.net/qASPe where a square moves towards a sphere after 5 seconds. The code snippet used in this example is:

new TWEEN.Tween(ship.position)
    .to(planet.position, 700) // specify destination and duration
    .start();

For more complex animations, you might consider utilizing a THREE.Curve or other path mechanisms. For instance, you can refer to this demo at http://jsfiddle.net/aevdJ/12 for creating a flying path.

// Define a path
var path = new THREE.SplineCurve3([
    ship.position,
    // Define additional points representing the trajectory
    planet.position
]);

new TWEEN.Tween({ distance: 0 })
    .to({ distance: 1 }, 3000) // specify destination and duration
    .onUpdate(function() {
        var pathPosition = path.getPointAt(this.distance);
        ship.position.set(pathPosition.x, pathPosition.y, pathPosition.z);
    })
    .start();

Remember to include the following line in your update function:

TWEEN.update();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to modify the colors of two specific elements using a combination of CSS and JavaScript

I am currently developing a browser-based game and have encountered an issue. Here is the relevant line of my HTML/PHP code: echo '<div id="div'.$n.'" class="d'.$rand.'" onclick="swapit(this.id, this.className)"></di ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

Can a static text be displayed randomly using Javascript?

What I'm searching for is a unique text display feature that's different from scrolling. I envision a subtle fade in/out effect, but it's not necessary. The main goal is to fit within a small area on a website with limited vertical space - ...

In React + TypeScript, learn how to effectively pass down a function from a container component to a

I am currently working on developing a tabs application using React and Typescript. The main component, Tabs, manages the state and passes it down to the Content component. Additionally, I have implemented a function called 'handleName' which is ...

When using Jquery, the search button consistently retrieves the same data upon the initial click event

How can I ensure that my Ajax call retrieves data from the remote database based on the updated search criteria every time I click the search button? Currently, the system retrieves results based on the initial search criteria even after I modify it and cl ...

Unexpected behavior in VueJS code - troubleshooting the issue

In my VueJs code, I have a simple task list with completed and incomplete tasks. When I check or uncheck the box, the task should move to the appropriate list. var app = new Vue({ el: '#vueapp', data: { tasks: [{ id: 1, ...

Using a switch statement for camera tween in three.js

Attempting to animate a camera in three.js involves the following code in the init function, utilizing a switch statement passed through an iFrame. window.onmessage = function(evt) { switch (evt.data.cameraYpos) { case 'Ypos01&ap ...

Rendering items in a list with React does not just display the last item on the list

I encountered an issue where, when I retrieve data from an API and add it to the state's array, I only see the last list item even though the mapping process is supposed to include more than 1 item. const [items, setItems] = useState([]); con ...

Building Nested Divs with JavaScript

I've encountered an issue with this code snippet. While it works perfectly fine in jsfiddle, I faced a problem when testing it on my local file. Only the first three lines created by html are displayed: test h1 test h2 test p (I tested the code ...

Geometry is making its debut appearance in ThreeJS for the very first time!

Currently, I am experimenting with a simple script using ThreeJS to create a point wherever you click on the screen. Below is the function responsible for adding the point: function addPoint(coord){ var geometry = new THREE.BufferGeometry(); var verti ...

Importing a JSON or JSONC file into a vite/typescript project can be easily done

I am looking for a way to seamlessly share my routes between my actix-web backend and Vue with Vue-Router frontend without needing separate route files. I want to define the routes on the frontend without having to make any changes on the server side. If t ...

Is it possible to set the input form to be read-only?

I need to create a "read-only" version of all my forms which contain multiple <input type="text"> fields. Instead of recoding each field individually, I'm looking for a more efficient solution. A suggestion was made to use the following: <xs ...

Implementing the sticky positioning property to keep a div container fixed at the bottom of the page

As Bootstrap 4 no longer supports .affix, I had to look for an alternative solution to keep a box fixed. I needed a div container to remain fixed as you scroll to it. My current workaround is using: .fixedcard{ position: sticky; top:75%; } However, th ...

The Zip file generated in memory is experiencing corruption

I'm encountering an issue while attempting to serve a zip file generated in memory by Flask to a JavaScript front-end. However, the downloaded file appears corrupted and I am unsure of what mistake I may be making. @app.route('/route') def ...

The controller returned a null value

I've encountered a situation where I'm utilizing a service file to execute a stored procedure: function createCampaign($campaignName, $groupNumber){ $stmt = \DB::connection('odbc')->getPdo()->prepare('CALL SCHE ...

Exploring the World of Angularjs 2

Currently, I am diving into learning angularjs 2. I found a helpful git repository that I am following closely, which can be found here. The repository contains some interesting codes in the index.html file. <script src="node_modules/core-js/client/shi ...

Ways to incorporate a custom JavaScript function that is activated by an external server system?

I'm currently exploring a JavaScript widget that needs to operate within specific constraints: The widget initiates a request to a third-party server using a callback URL The third-party server pings the callback URL after a set period, triggering a ...

Implementing Text Box Control Validation within a Gridview using UpdatePanel in c# ASP.Net

In my gridview, one of the columns contains a Text Box Control. I am looking to validate the text entered by users as alphanumeric characters and spaces only. Allowed characters are: a-z, A-Z, 0-9, and space. I want to perform this validation using Java ...

Tips for retrieving data from a JSON array

I have a JSON object that looks like this: var obj={ "address":{ "addlin1":"", "addlin2":"" }, "name":"sam", "score":[{"maths":"ten", "science":"two", "pass":false }] } Now, when I attempt to m ...

Currently, I am developing a Vue.js chat application. I am facing a challenge when it comes to sending the entire input div along with the keyboard popping up on Android devices. How can I achieve this

I'm in the process of developing a chat application using vuejs that will be accessed through a webview on Android. I currently have an input-bx element for sending messages, but I need to find a way to ensure it remains visible when the Android keybo ...