Spinning points about a center point

My goal is to rotate 4 points around a specific origin. Initially, the points appear in the correct position without any rotation. The code for this initial positioning is as follows:

let origin = this.transform.position;
for (let i in this._pointsOrig) {
    let point = this._pointsOrig[i];
    this._points[i] = new Vector2(
        point.x + origin.x,
        point.y + origin.y
    );
}

This code produces the following output:

Note: In the visualization, the blue cross represents the origin, and the green rectangle outlines the points.

https://i.sstatic.net/lxj9y.png

However, when I attempt to introduce rotation to the rectangle with the following code:

// degrees is between 0 & 360, so convert to radians
let rotation = this.transform.rotation.degrees * (Math.PI / 180);
let cos = Math.cos(rotation);
let sin = Math.sin(rotation);
let origin = this.transform.position;

for (let i in this._pointsOrig) {
    let point = this._pointsOrig[i];
    this._points[i] = new Vector2(
        (cos * (point.x - origin.x)) + (sin * (point.y - origin.y)) + origin.x,
        (cos * (point.y - origin.y)) - (sin * (point.x - origin.x)) + origin.y
    );
}

The result shifts the rectangle to the bottom left corner, as shown below:

https://i.sstatic.net/LbEFB.png

I am currently unsure about how to ensure that the points rotate effectively around the intended origin.

Answer №1

One approach to consider is:

(cos * point.x) + (sin * point.y) + origin.x,
(cos * point.y) - (sin * point.x) + origin.y

It appears that the values of point.x and point.y are not adjusted for the shift by (origin.x,origin.y). Thus, shifting coordinates before rotation may lead to unexpected results.

You may notice that the rotation is occurring in the opposite direction with this transformation:

(cos * point.x) - (sin * point.y) + origin.x,
(cos * point.y) + (sin * point.x) + origin.y

To correct this, try changing the signs accordingly.

If the rotation angle is always 90°, you can simplify the calculations as follows:

this.points[i] = new Vector2(
    - point.y + origin.x,
      point.x + origin.y );

If issues persist, providing actual values for origin, _pointsOrig[i], and the final result could be helpful in troubleshooting.

Answer №2

Before rotating, adjust _pointsOrig so that they are properly centered around the coordinate origin.

Once centered, rotate the points and then shift them back based on your chosen origin point.

point.x  = point.x - left + width / 2
point.y  = point.y - top + height / 2
this._points[i] = new Vector2(
    (cos * point.x + sin * point.y) + origin.x,
    (cos * point.y - sin * point.x) + origin.y

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

"Utilizing Rails 3 to initiate an AJAX submit when radio buttons are changed leads to the generation of

Need help with Rails 3 form partial <%= form_for(answer, :remote => true) do |f| %> <% if answer.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(answer.errors.count, "error") %> prevented this ans ...

Tips for modifying a user's tags with Quickblox's JavaScript SDK

Is there a way to update a user's tags using the Quickblox JavaScript SDK? I have attempted using the parameter names listed below: user_tags tags with var params = { user_tags: ["testing"] }; Kindly avoid suggesting alternatives like "custom ...

Reduce and combine JavaScript files without the need for Grunt or Gulp

My project involves working with over 50 JavaScript files that I want to combine and compress to optimize file size and minimize HTTP requests. The catch is, the client's system does not have Node or npm installed. How can I accomplish this task witho ...

"Troubleshooting tip: encountering a SyntaxError message stating 'import declarations may only appear at top level of a module'? Here's

After downloading fetch-jsonp by running npm i fetch-jsonp and adding its dependency to my package.json, I attempted to import it using the following code at the top of my main.js: import fetchJsonp from 'fetch-jsonp'; However, I kept encounter ...

JavaScript file encountering a problem with its global variables

What is causing the alert("2") to pop up first instead of it being second? Why am I encountering difficulty creating global variables c and ctx? Is there a way for me to successfully create these two global variables in order to utilize ...

Creating a custom arrow design for a select input field using CSS

I'm currently developing a website (using Wordpress with a custom theme) and I want to incorporate an up/down arrow in the select input field using CSS. The HTML code I have for creating the up/down arrow in the select input field is as follows: < ...

I seem to be facing some difficulty in dynamically calling my buttons in AngularJS

Can you assist me in solving this problem? I am new to Angular and just starting out. Initially, there is only one button on load called "Add list". When the user clicks on this button, they are able to add multiple lists. Each list contains a button labe ...

Can you explain the process of accessing data from [[PromiseValue]] while utilizing React hooks?

My current challenge involves fetching data from an API and utilizing it in various components through the Context API. The issue arises when I receive a response, but it's wrapped under a Promise.[[PromiseValue]]. How can I properly fetch this data ...

What is the rationale behind angular-fullstack's decision to implement both put and patch requests in Express?

I recently stumbled upon an article discussing the distinctions between PUT and PATCH requests (Difference between put and patch). Though I've gained some clarity on the topic, there are still aspects that remain unclear to me. One of my major querie ...

Is there a way to access a JSON node dynamically without relying on the eval function?

Path variables can be unpredictable, ranging from just a to a/b, and even a/b/c. My goal is to dynamically reach a node based on the path provided. The code snippet below achieves this, but I am open to exploring alternative methods that do not involve usi ...

Is there a method for establishing a connection to oracledb using TypeScript ES6 class and module?

My goal is to implement an Oracle connection using Typescript ES6 Class module. I have successfully installed the @types/oracledb package and oracledb package, with the Jasmin framework used in my project. Below is the code I have implemented: import * ...

Navigate through dropdown options using arrow keys - vuejs

I am currently working on creating an autocomplete feature using Vue.js. However, I have run into an issue with the scroll animation. The goal is to enable scrolling by clicking on the arrow keys in the direction of the key pressed, but the scroll should ...

Displaying records up to the year 1427 only

I am facing an issue while trying to populate data from a database into an HTML table using JSON and C#.NET. The problem I am encountering is that only up to 1427 records are being displayed, and I keep getting the error message "Unexpected token <". De ...

What is the best way to organize angularjs controllers and directives within one another?

When I structure my controllers like this: <body ng-app="app" ng-controller="ctrl"> <div ng-controller="app-get"> <app-get></app-get> </div> <div ng-controller="app-post"> <app-post">& ...

Durandal attempts to retrieve a view located within the viewmodel directory

Having an issue with durandal's compose binding as it is looking for views under app/viewmodels instead of app/views The ViewModel code: define(["fields/fieldClosures"], function (fields) { var ctor = function(opt) { this.value = opt.valu ...

Using Node.js to read from a file and write the character 'Ł' to another file

I am facing an issue with an ANSI file that contains the character 'Ł'. My goal is to extract this character and save it to another file while preserving the same encoding to retain the 'Ł' character. const fs = require('fs&apos ...

Activate a Bootstrap tab using turbolinks dynamically

After loading the page, I am attempting to open a Bootstrap 4 tab. It works when I refresh the page, but if I navigate within the site, it gives me a query selector empty error. This code is a port of the solution mentioned in this tutorial, as I am using ...

Methods for verifying an empty array element in TypeScript

How can I determine if an element in an array is empty? Currently, it returns false, but I need to know if the element is blank. The array element may contain spaces. Code let TestNumber= 'DATA- - -' let arrStr =this.TestNumber.split(/[-]/) ...

Traverse the array containing nested arrays to generate fresh objects in AngularJS

After retrieving an object from my REST API, I need to iterate over the array and create new objects/arrays from it. The structure of the array is as follows: orderItem contains menu_modifier_groups, which in turn contain menu_modifier_items. The hierar ...

When utilizing the vue @submit directive, the FormData object may be found to be devoid

Encountering a unique edge case, I found a solution. When creating a form with Vue, I noticed that empty strings were being sent to the server. Upon investigation, it became apparent that the issue lies within the @submit directive. Interestingly, when uti ...