What could be the reason my homing missile algorithm is not functioning properly?

The code I'm currently using for my projectile was heavily inspired by an answer I found on a game development forum, but it's not working as expected. Most of the time, the initial direction of the projectile is perpendicular to the target instead of homing in on it. Sometimes, it does start moving towards the target after passing by, but then it seems frozen at a certain point before catching up to the target with unusual movement. There's a line of code that I suspect might be causing the issue, where V3 and V4 variables are used in the algorithm, which seems like a potential typo. If anyone could provide some guidance on what might be going wrong here, I would greatly appreciate it.

normalizedDirectionToTarget = root.vector.normalize(target.pos.x - attack.x, target.pos.y - attack.y) #V4
V3 = root.vector.normalize(attack.velocity.x, attack.velocity.y)
normalizedVelocity = root.vector.normalize(attack.velocity.x, attack.velocity.y)

angleInRadians = Math.acos(normalizedDirectionToTarget.x * V3.x + normalizedDirectionToTarget.y * V3.y)
maximumTurnRate = 50 #in degrees
maximumTurnRateRadians = maximumTurnRate * (Math.PI / 180)
signOfAngle = if angleInRadians >= 0 then 1 else (-1)
angleInRadians = signOfAngle * _.min([Math.abs(angleInRadians), maximumTurnRateRadians])
speed = 3
attack.velocity = root.vector.normalize(normalizedDirectionToTarget.x + Math.sin(angleInRadians), normalizedDirectionToTarget.y + Math.cos(angleInRadians)) #I'm very concerned this is the source of my bug
attack.velocity.x = attack.velocity.x * speed
attack.velocity.y = attack.velocity.y * speed
attack.x = attack.x + attack.velocity.x
attack.y = attack.y + attack.velocity.y

Edit: Code that Works

normalizedDirectionToTarget = root.vector.normalize(target.pos.x - attack.x, target.pos.y - attack.y) #V4
normalizedVelocity = root.vector.normalize(attack.velocity.x, attack.velocity.y)
angleInRadians = Math.acos(normalizedDirectionToTarget.x * normalizedVelocity.x + normalizedDirectionToTarget.y * normalizedVelocity.y)
maximumTurnRate = .3 #in degrees
maximumTurnRateRadians = maximumTurnRate * (Math.PI / 180)
crossProduct = normalizedDirectionToTarget.x * normalizedVelocity.y - normalizedDirectionToTarget.y * normalizedVelocity.x
signOfAngle = if crossProduct >= 0 then -1 else 1
angleInRadians = signOfAngle * _.min([angleInRadians, maximumTurnRateRadians])
speed = 1.5
xPrime = attack.velocity.x * Math.cos(angleInRadians) - attack.velocity.y * Math.sin(angleInRadians)
yPrime = attack.velocity.x * Math.sin(angleInRadians) + attack.velocity.y * Math.cos(angleInRadians)
attack.velocity = root.vector.normalize(xPrime, yPrime)
attack.velocity.x *= speed
attack.velocity.y *= speed
attack.x = attack.x + attack.velocity.x
attack.y = attack.y + attack.velocity.y

Answer №1

My perspective is that when you have a vector represented by coordinates (x,y) and you wish to rotate it by an angle 'theta' around the origin, the resulting vector (x1,y1) can be calculated as:

x1 = x*cos(theta) - y*sin(theta)

y1 = y*cos(theta) + x*sin(theta)

(this transformation can be understood through polar coordinates)

UPDATE: If you are aware of the speed and the magnitude of the final angle (let's call it phi), why not simply calculate it as follows:

Vx = speed*cos( phi )

Vy = speed*sin( phi )

UPDATE 2: Keep in mind that when taking the inverse cosine, there may be multiple potential angles in radians. It's essential to consider the quadrant in which both vectors exist. The maximum turning rate is 50 degrees in either direction, so the cosine value for that angle will always be positive. (The cosine function is negative between 90 to 270 degrees.)

UPDATE 3: To determine whether the turn direction is positive or negative, employing the cross product method could be more effective.

UPDATE 4: Utilizing Vx / Vy should yield results if you follow these steps:

initialAngleInRadians = Math.atan(normalizedVelocity.y / normalizedVelocity.x)
finalAngleInRadians = initialAngleInRadians + angleInRadians
Vx = speed*cos(finalAngleInRadians)
Vy = speed*sin(finalAngleInRadians)

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

Retrieve information and auto-fill text boxes based on the selected dropdown menu option

UPDATED QUESTION STATUS I'm currently working with Laravel 5.7 and VueJs 2.5.*. However, I am facing a challenge where I need to automatically populate form textboxes with data from the database when a dropdown option is selected. Despite my efforts ...

Transferring data to a child component through Route parameters

Although I have come across numerous questions and answers related to my query, I still seem unable to implement the solutions correctly. Every time I try, I end up with an 'undefined' error in my props. Let's take a look at my parent compo ...

Implementing a color change for icons in React upon onClick event

export default function Post({post}) { const [like,setLike] = useState(post.like) const [islike,setIslike] = useState(false) const handler=()=>{ setLike(islike? like-1:like+1 ) setIslike(!islike) } return ( <> <div classNam ...

The GAS web application is experiencing issues with sorting dates correctly on the Javascript table

I have a food consumption log in a table that I need to sort. When I attempt to sort by the date column, I notice an issue with how it groups numbers together. For example, the sorting places all dates starting with 10 between 1 and 2, then all dates star ...

Adding a new row to a Bootstrap table while maintaining the consistent style

Is there a way to dynamically add a new table row with different styling using jQuery? I'm facing this particular issue and need help in solving it. Below, I have included some screenshots of my code and the view for better understanding. Here is the ...

What is causing the error message 'Unexpected use of 'location' no-restricted-globals'?

When working on my reactjs code, I encountered the following issue: const { children, location: { pathname }, } = this.props; let path = location.pathname; I am also utilizing the react router module in this component. Anyone have suggestions on how ...

Firefox is mistakenly interpreting a pasted image from the clipboard as a string instead of a file, causing

I am facing an issue where I am attempting to extract images from a contenteditable div using the paste event. The code works perfectly in Chrome but does not function as expected in Firefox. I have implemented the following code: $(window).on("paste& ...

Passing "this" to the context provider value in React

While experimenting with the useContext in a class component, I decided to create a basic React (Next.js) application. The app consists of a single button that invokes a function in the context to update the state and trigger a re-render of the home compon ...

Organizing seating arrangements for a concert hall performance

My goal is to develop a custom concert seat booking system using HTML, CSS, and JavaScript. For example, if the concert venue has 10 rows with 20 seats in each row, I could organize them like this: const rows = [ { name: 'A', seats: [1, 2, 3, ...

Ways to specify an unused parameter within a function

As I work on my code, I encounter the need to separate the key and value from a request params object in order to validate the value using ObjectID. To achieve this, I decided to iterate over an array of entries and destructure the key and value for testin ...

Analyzing the functionality of Express with Mocha and Chai

Currently facing an issue with testing my express server where I am anticipating a 200 response. However, upon running the test, an error occurs: Test server status 1) server should return 200 0 passing (260ms) 1 failing 1) Test server statu ...

ExpressJS and cookies - Struggling to initialize a cookie with express-cookie

I recently followed a tutorial on YouTube (https://youtu.be/hNinO6-bDVM?t=2m33s) that demonstrated how to display a cookie in the developer tools Application tab by adding the following code snippet to the app.js file: var session = require('express- ...

The children of the KendoUI treeview are showing up as null

Within my KendoUI treeview setup, the main nodes trigger a call to an MVC controller that checks for a nullable ID parameter before utilizing a different model. When accessing the URL: http://localhost:2949/Report/GetReportGroupAssignments The resulting ...

Image not showing up on HTML page following navigation integration

Having trouble with my responsive website setup - the background image for ".hero-image" isn't showing up after adding the navigation. Google Chrome console is throwing a "Failed to load resource: the server responded with a status of 404 (Not Found)" ...

Having trouble getting a ForEach loop to work within promises when using mongoose?

Hey everyone! I'm diving into the world of nodeJs and working on a project that involves pushing certain values into an array. Unfortunately, my code isn't behaving as expected, and I suspect it has something to do with promises. Here's the ...

An unexpected page transition occurs when attempting to delete a link

I've successfully created an HTML table that dynamically adds rows and provides an option to delete the current row. Each row represents data retrieved from MongoDB, and upon clicking the delete button, I aim to delete the corresponding item from the ...

Retrieve the current state within a redux action

Many experts recommend consolidating the logic in action creators to streamline the reducer's logic. Picture a basic (normalized) state: const initialState = { parent: { allIds: [0], byId: { 0: { parentProperty: `I'm the ...

Issue encountered: Unable to load resource - ajax file upload failed due to net::ERR_SSL_BAD_RECORD_MAC_ALERT error

I've implemented an AJAX form file upload using jQuery. After testing my code across multiple computers and browsers, I've encountered an issue on one Windows 8 machine running Chrome where the upload functionality fails with the following error ...

Minimize the cyclomatic complexity of a TypeScript function

I have a typescript function that needs to be refactored to reduce the cyclometric complexity. I am considering implementing an inverted if statement as a solution, but it doesn't seem to make much of a difference. updateSort(s: Sort) { if (s.ac ...

Update the variable in a PHP script and execute the function once more without the need to refresh the page

Hey there, I'm wondering if AJAX is necessary for the functionality I want to implement. Here's the scenario: I have a function that generates a calendar and I plan to add 'forward' and 'backward' arrows so users can navigate ...