Limiting Velocity in a Two-Dimensional Spacecraft

Like many others diving into the world of programming, I decided to challenge myself with a spaceship game project. At this point, I have successfully incorporated parallax stars and other essential features expected in a space-themed game. The spacecraft remains centered on the screen, capable of rotating 360 degrees, accelerating, coasting, and moving around like an object in outer space should. However, one small issue persists – capping the ship's speed.

The ship operates with dx and dy values that translate its movement through my update() function. It applies thrust along either the x or y axis depending on the current angle it faces. I have set a maximum speed (let’s say 5) and an acceleration rate (0.1 per frame). When thrusting, the ship accelerates as anticipated. Since I am using digital input controls (arrow keys), the thrusters are always at full power without throttle control. To determine the ship's velocity, I check the hypotenuse of the triangle created by its current dx and dy, and I also track its travel angle for future AI implementation, weapons firing, and autopilot-like braking when pressing the down arrow.

Some of the key variables governing the ship's movement include:

x_speed
y_speed
speed
move_angle // Tracks motion direction
face_angle // Determines x_accel and y_accel during thrusting
x_accel
y_accel
accel = 0.1 // Multiplied by the dx and dy from getDxDy(face_angle)
max_x
max_y
max_speed = 5 // Multiplied by the dx and dy from getDxDy(face_angle)

I employ the following function to obtain the dx and dy based on the face_angle:

function getDxDy(degree)
{
var dx;
var dy;
var degree = degree;

dx = -Math.sin(degToRad(degree));
dy = Math.cos(degToRad(degree));

var dxdy = {
    dx: dx,
    dy: dy
};

return dxdy;
}

Each frame, I update the speed with acceleration as follows:

x_speed += x_accel
y_speed += y_accel

I attempted various methods to cap the speed and experimented with checks such as:

if (x_speed > max_x)
{
    x_speed = max_x
}

and:

if (x_speed > max_x)
{
    x_speed -= x_accel
}

The initial approach succeeded in capping the speed but restricted further acceleration modifications or caused sudden reversals in speed when changing directions due to constant recalculation of max_speed based on the ship's face_angle. The second method resulted in unwanted negative thrust upon stopping, leading to unintended acceleration in the opposite direction.

My goal is to limit thrust to a specific value (e.g., 5) regardless of direction and ensure that the ship gradually adjusts its trajectory after a change in direction. Furthermore, I aim for realistic deceleration when reversing thrust.

If you’ve ever played Escape Velocity, you’ll recognize the movement and control system I aspire to recreate as my "Gold Standard."

You can view my code, which is somewhat functional, at

For the specific .js file associated with this issue, visit . Please excuse the clutter of commented-out code as I've dedicated a week to tackling this particular aspect.

Although I explored numerous online solutions, those aligning closely with my design primarily employ the first "if" statement provided above, proving ineffective for me. Additionally, I reviewed related inquiries on StackOverflow:

2D Spaceship movement math

2d trajectory planning of a spaceship with physics

Programming a smooth change of thrust from current velocity vector to a target vector

While these solutions offer valuable insights, they seem complex for my needs. Omitting any gravity system, unlike the first example, the remaining suggestions do not immediately address my specific dilemma.

I welcome basic pseudocode or any guidance direct towards overlooked resources addressing my query. While I seek resolutions compatible with my existing setup, I am open to slight adjustments in my ship's movement logic if it streamlines the max_speed restriction process.

Thank you sincerely for engaging with this comprehensive explanation. :)

UPDATE:

After refining my code with some adjustments, it now operates more effectively than before. Refinements, tweaking, and debugging remain to achieve perfection. :)

Answer №1

When I switch the calculation to the move angle, it causes issues at the beginning when the ship is stationary.

To prevent this problem, set your initial values for dx, dy, x_speed, and y_speed to 0. Let the x_speed and y_speed determine the move angle instead of maintaining a separate move_angle.

If my interpretation of your setup is incorrect, consider starting with speed at 0 and perform calculations that do not involve trigonometry when the speed value is below a certain threshold.

Alternatively, you can handle most of the velocity and acceleration computations in polar values and convert them to Cartesian coordinates only when displaying on the screen.

My apologies if I seem a bit disoriented, as it's my least productive time of the day and I'd rather be napping than sitting at my desk right now.

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

5 steps to create a versatile function for activating attributes based on their values

Hey everyone! I was working on creating this calculator and I had different options to implement it, but I wanted to do it in a specific way. <form action=""> <label for="num1">Number A</label><br> <input type="number" na ...

Having trouble retrieving the ID of the clicked element in AngularJS?

I have successfully implemented a function in angularjs to retrieve the id of the clicked element. Below is my code snippet html <a href="#faqinner/contactform" class="clearfix" ng-click="getCateId($event)" id="{{option.id}}"> <span class= ...

Fetching a collection from Cloud Firestore using Angular and Firebase

I'm looking to figure out how to retrieve lists from cloud firestore. Here is how I upload a list : export interface Data { name: string; address: string; address2: string; pscode: string; ccode: string; name2: string; } constructor(pri ...

Utilize AngularJS to Access Global JavaScript Variables

I recently encountered a situation where I needed to incorporate some dynamic functionality into a website I was building. This led me to AngularJS, which I decided to integrate into certain parts of the site rather than the entire thing. Within my JavaSc ...

Tips on sending filter parameters from AngularJS to Spring RestController using @MatrixVariable

I’m struggling to figure out how to use $http.get in AngularJS to pass filter parameters. The URL is: http://localhost:8080/template/users/query;username=abcd;firstName=ding... The RestController looks like this: @RequestMapping(value={"/users/{query ...

Utilizing onClick with material-ui button - functioning flawlessly for a single interaction

I have been attempting to encapsulate a Material-UI button within another component. Everything seems to be working well, except for when I try to handle the onClick event - it appears to only work once. Here is an example that demonstrates the issue: ht ...

Avoid executing top-level path middleware with app.use('/') in Express routing when directly accessing child or nested paths

Perhaps the title may not be as accurate as I hoped, but I have a very simple example to share. On my website, there are two main areas - a public area and a restricted admin area. example.com/admin (admin home page) example.com/admin/news (news page) ...

JavaScript can be used to activate the onclick event

Is there a way to disable and then re-enable all buttons that share the same class name? I attempted the following code without success: let buttons = document.getElementsByClassName("btn-st"); for (let i = 0; i < buttons.length; i++) { b ...

Exploring Substrings in jQuery/JavaScript

Issue Can anyone help me with locating a specific set of words within a string (gval in this scenario) that defines the specific wordset? if (gval.indexOf("define") > -1){ console.log("Hey! gval has Define"); } var gval = input.val().trim().toLowe ...

The function toggleClass() is malfunctioning

The .toggleClass() method seems to only be adding the "class" attribute to my selection, resulting in: <div id="toggle" class> ... rather than: <div id="toggle" class="on"> ... I've been trying to solve this issue for about 2 hours now ...

"Exploring the Differences between JavaScript, AJAX, and Servlet for String

I am attempting to compare a string that is received from a servlet. The servlet page returns the following: out.println("pass"); In JavaScript: function Check() { if (ajax.responseText === "pass") { document.getElementById("pass").innerHTML = "This is ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

Does using .detach() eliminate any events?

I have a DIV that is filled with various content, and I am using the detach() and after() functions to move it around within the document. Before moving the DIV, I attach click events to the checkboxes inside it using the bind() function. Everything seems ...

Can GET or POST variables be transmitted to external JavaScript?

Is it possible to pass a variable to an external JavaScript file? For instance: Suppose I have the following code: <script type="text/javascript" src="gallery.js"></script> I'm curious to know if it's feasible to pass an argument ...

NPM Package Encountering Module Parsing Issue

I encountered a strange error while building my project with Webpack. The error is related to the Got package that I am trying to import from its `package.json` file. Module parse failed: .../node_modules/got/package.json Unexpected token (2:8) You may ne ...

Is there a way to use JavaScript to add content to a document and then facilitate the download of that document?

Is there a way in JavaScript to write content to a JSON or TXT file and then download it, similar to how it is done in Python? const content = "Hello"; const link = document.createElement('a'); link.setAttribute('download', 'FileTo ...

What steps should I take to resolve the issue with this error message: Error: listen EADDRINUSE

How can I resolve the following issue? system: gulp npm windows issue: ... Oh no. Encountered error listen EADDRINUSE 127.0.0.1:35729 ... Error: listen EADDRINUSE 127.0.0.1:35729 at Object._errnoException (util.js:1021:11) at _exce ...

VARIABLE_NAME isn't functioning properly on the window

The code window.VARIABLE_NAME is not functioning properly and is causing the following error. Can you please provide assistance? Uncaught SyntaxError: Unexpected token. This is the code I have written: var window.testing ...

The tooltip in a scrollable container of Highcharts moves along with the content as it scrolls

I am currently facing an issue with my Highcharts instance that is displayed within a scrollable container. In addition, I have set the tooltip.outside option to true so that the tooltip always appears on top even if it exceeds the chart svg. The problem ...

Using curly braces in a fat arrow function can cause it to malfunction

Could someone provide insight into why this code snippet functions as intended: filteredArray = contacts.filter( (contact: Contact) => contact.name.toLowerCase().includes(term.toLowerCase()) ); while this variation does not: filteredArray = contact ...