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

First Impressions of Datatables

Is there a way to display a specific range of rows with Datatables initially? For example, showing rows 100-105 only. Does anyone know if this is achievable using the options available? ...

We are sorry, but the requested route cannot be located

I'm diving into the world of express and trying to set up subroutes for a specific "plan" with corresponding actions. My journey begins at mypage.com/someroute/123321312 router.get('/:planId', function(req, res, next) { //a form is render ...

Combining the inline JavaScript linting tool ESLint with the popular Airbnb configuration and Facebook

In my current project, I am utilizing ESLint and looking to incorporate Facebook flow. However, I am encountering warnings from ESLint regarding flow type annotations. Within the project root directory, I have both .flowconfig and .eslintrc files present. ...

Why is the click function being invoked twice, but exclusively on the initial click?

In my current project, I am facing an issue with the onClick action that is being passed down from Context. Strangely, when this action is clicked for the first time, it fires twice. However, from the second click onwards, it functions normally and only fi ...

How can I troubleshoot the overflow-y problem in a tab modal from w3 school?

https://www.example.com/code-sample overflow: scroll; overflow-y: scroll; When I type a lot of words, they become hidden so I need to use overflow-y=scroll. Despite trying both overflow: scroll; and overflow-y: scroll;, I have been unable to achieve the ...

Clear the local storage once the URL's view has been fully loaded

When retrieving details of a specific item by passing URL parameters stored in local storage, I encountered an issue. I need to delete the local storage variables after the view is loaded. However, what actually happens is that the local storage variable ...

Disable Autocomplete Chip functionality when only one can be selected

When multiple is set to true, I prefer the Chip option. Is there a way to enable the Chip functionality even when multiple is set to false? <Autocomplete className={classes.search} options={top100Films} ge ...

Searching for the perfect jQuery regex to validate date formats

In my application, there is an input box that allows users to enter a string date like "today" or "tomorrow". However, I am facing a new challenge now - dates such as "3 march" or "8 january." The input box includes a dropdown menu feature where users can ...

Tool for controlling the layout of the viewport with Javascript

I have experience using ExtJS in the past to create dashboards, and one of my favorite features is the full-screen viewport with a border layout. This allows for easy splitting of a dashboard into panels on different sides without creating excessive scroll ...

Chaining inheritance through Object.create

Recently, I decided to experiment with Object.create() instead of using new. How can I achieve multiple inheritance in JavaScript, for example classA -> classA's parent -> classA's parent's parent, and so on? For instance: var test = Objec ...

Comparing the use of Next.js static assets from the public folder with cloud-based storage solutions

Typically, in Next.js (or React) cloud-based storage solutions are commonly utilized for storing media files such as images. My inquiry is, what prevents us from saving images as static assets in the public folder and accessing them directly in our appli ...

When I try to access localhost, it directs me to http://localhost:3000/myprofile%20 instead of localhost:/3000/myprofile

Every time I try to log into my profile page with the correct login credentials, I get redirected to http://localhost:3000/myprofile%20, but then receive a 404 error. This is what my code looks like: // Login Route router.post('/login', functi ...

Identify Horizontal Swipe Gestures on Page-level

I am currently focused on ensuring accessibility for users utilizing voiceover technology. While navigating their phone, these individuals rely on right and left swipes to interact with elements on a page. I am seeking to implement swipe detection at the ...

Exploring JSON Data with Mustache Templates

Dealing with a significantly large JSON object that I can't control, I'm struggling to output a list of records (related to people in this case) using Mustache.js. Despite simplifying the complex object into a more manageable one with just the ne ...

Issue with extended waiting times in polling

I am currently working on a chatroom using the long poll method. However, I'm facing an issue where every time a long poll occurs and I refresh the page in Chrome or try to send another async request, everything times out. This means I can't load ...

Learn how to properly implement cookies in a fetch request within Nextjs

Here is a code snippet to consider: Index.getInitialProps = async function({req}) { const res = await fetch("http://localhost/api/tiles"); const json = await res.json(); } If the /api/tiles endpoint requires access to the uid cookie from the user, t ...

Troubleshooting Autocomplete User Interface Problems

I am currently working on a website user interface and I have encountered an issue specifically in IE7. When searching for a company, the display is not showing up correctly, as demonstrated in the image below. This problem only occurs in IE7, it works fi ...

Interactive JQuery plugin for scrolling through thumbnails with customizable buttons

I am attempting to create a jQuery thumbnail scroller with buttons that respond to mousedown and mouseup events. I have successfully implemented the scrolling functionality, but I am facing issues when trying to refactor it into a reusable function. Below ...

How to Access a div from another website using jQuery

I have a question. How can I call a div from another website using JavaScript? Here is the page: Now, I want to call the <div id="testa"> in another page. The other page is called Otherpage.html: jQuery(function($){ $(&ap ...

Automatically Resizing an iFrame Height Upon Submit Button Click

Currently, I am facing an issue with a form that generates an iFrame for the Payment section. While the height of the iFrame is set correctly, whenever there are errors in the form submission and error messages appear, they push the submit button below t ...