unity – Why the rotation using the Coroutine is rotating but the object is in slant ? and how to rotate it with Coroutine non stop?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spin : MonoBehaviour
{
    public Vector3 targetRotation;
    public float duration;
    public bool spinInUpdate = false;

    // Start is called before the first frame update
    void Start()
    {
        if (spinInUpdate == false)
        {
            StartCoroutine(LerpFunction(Quaternion.Euler(targetRotation), duration));
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (spinInUpdate == true)
        {
            transform.Rotate(new Vector3(0, 1, 0));
        }
    }

    IEnumerator LerpFunction(Quaternion endValue, float duration)
    {
        float time = 0;
        Quaternion startValue = transform.rotation;

        while (time < duration)
        {
            transform.rotation = Quaternion.Lerp(startValue, endValue, time / duration);
            time += Time.deltaTime;
            yield return null;
        }
        transform.rotation = endValue;
    }
}

slant I mean this is how it’s rotating with the Coroutine the small cube that rotate is in slant :

slant

When using the Update way it’s rotating fine and this is how it should rotating also with the Coroutine for example on the X only :

Cube

The small cube when rotating either in update or in the Coroutine should not be slant. but it’s slant in the Coroutine.

And how can I add a speed factor to the Update to control the rotation in the Update in case using the Update ?

About controlling the speed in the Update I just added a global float variable and in the Update :

transform.Rotate(new Vector3(0, Time.deltaTime * rotationSpeed, 0));

and it’s working for the speed.

mathematics – Rotate relative to set point in a specified direction in a 3D space

I know there’s a geometry formula to calculate the next point in rotation relative to another point in 2D but I’m working in 3D and I want to calculate the next position in specified direction as well. Think Spiderman or the Bloodstalkers from ARK. I’m working in a game engine that uses the basic {x = 1, y = 2, z = 1} for vectors. I’m pretty bad at math so I honestly can’t figure this out myself.

unity – Rotate object relative to camera position

I am trying to write code that is able to rotate object, based on camera position. So far I ended up with a code posted below. Moving mouse up and down (y input) caused to rotate object in y axis, instead of x. That’s why I used cross product.

Achieved result is working not exactly as I expected. Rotation is different for every object, dependent on their pivot. I am not exactly sure how it fix it properly.

public class DragRotate : MonoBehaviour
{
    public Camera camera;
    public float rotationSpeed = 1;

    private void Update ()
    {
        float x = Input.mousePosition.x * rotationSpeed;
        float y = Input.mousePosition.y * rotationSpeed;

        var rot = camera.transform.TransformDirection (new Vector3 (x, y));
        rot = Vector3.Cross(rot, camera.transform.forward);

        transform.rotation *= Quaternion.Euler (rot);
    }
}

Using quaternions to rotate an object (OpenGl,c++)

I started to learn quaternions and got very weak idea of how they work. So I blindly followed some tutorials on you tube on how to rotate object with glm.
I had problem with weird rotations when I used Euler angles once I switched to Quaternions rotation was normal, but now rotation gets fuzzy in terms that it changes speed, when it should be constant.

glm::vec3* rotationAngles = modelVertex->getRotation();

glm::mat4 translate = glm::translate(glm::mat4(1.0f), *modelVertex->getPosition());


glm::mat4 mQuat = glm::mat4_cast(glm::normalize(glm::angleAxis(glm::radians(rotationAngles->x), glm::vec3(1.0, 1.0f, 0))));


return this->perspective *translate * mQuat;

rotationAngles->x is constantly increasing by some constant (20 degrees)

In my loop I have code that goes angle+=20; and then rotation.setXAngle(angle);

Funny thing is this only happens when I’m using rotation on both x-axis and y-axis, when for example I only rotate on x-axis,speed does not change.

OpenGL/C++ Rotate relative to shooting gun

Let us say you are shooting from p1 with coordinates p1.x and p1.y. And you want to shoot in direction to p2 with coordinates p2.x and p2.y.

When the bullet is created, you will place it in p1. That would be something like this:

bullet.position = p1;

We need to figure out how it should move.

Let us call d the vector that goes from p1 to p2:

d = p2 - p1
d = (p2.x - p1.x, p2.y - p1.y)

If you want the angle t, it will be t = atan2(d.y, d.x) or t = atan2(p2.y - p1.y, p2.x - p1.x) if you prefer. You don’t need the angle.

Let us say that the bullet should advance speed distance per unit for time. Then your velocity is:

velocity = d * speed/length(d)

That velocity describes the motion of the bullet. I’m assuming no gravity, as it was not mentioned in the question. I’m guessing this is a top down game.

I suggest to store it in the bullet:

bullet.position = p1;

var d = p2 - p1;
bullet.velocity = d * speed/length(d);

Each game cycle you will move the bullet by velocity according to the number of units of times elapsed. That would be something like this:

bullet.position = bullet.position + (bullet.velocity * delta);

where delta is the elapsed time in the same units used for l. For example l is pixels per millisecond and delta is milliseconds. If you are working with different units you need a unit conversion. For example if l is pixels per second, and delta is milliseconds, you need to divide delta by 1000 so it is in seconds.


The vector operations used:

  • Vector addition: v1 + v2 = (v1.x + v2.x, v1.y + v2.y)
  • Vector subtraction: v1 - v2 = (v1.x - v2.x, v1.y - v2.y)
  • Scalar product: v * s = (v.x * s, v.y * s)
  • Length: length(v) = sqrt(v.x * v.x + v.y * v.y)

Alright, let us suppose you are placing a model to represent the bullet, and you want to be able to apply a transformation to the model.

We want to have the orientation stored so we have use it to orient the model.

bullet.position = p1;

var d = p2 - p1;
bullet.direction = d * 1/length(d);
bullet.velocity = bullet.direction * speed;

Let us see how the rotation matrix transformation looks like:

+-                  -+
|  cos(θ)    -sin(θ) |
|                    |
|  sin(θ)    cos(θ)  |
+-                  -+

We already have those values:

+-                                          -+
|  bullet.direction.x    -bullet.direction.y |
|                                            |
|  bullet.direction.y    bullet.direction.x  |
+-                                          -+

And, of course, you would make your translation matrix from bullet.position.

There is no need to call any trigonometric function. No need to waste CPU cycles on them or introduce floating point errors due their computation.

Rotate the elements in an array in JavaScript

EDIT::
Hey so turns out there’s too much iteration happening. No loops, no branching.

Still works with negative n for right rotation and positive n for left rotation for any size n,
Mutation free

function rotate(A,n,l=A.length) {
  const offset = (((n % l) + l) %l)
  return A.slice(offset).concat(A.slice(0,offset))
}

Here’s the code golf version for giggles

const r = (A,n,l=A.length,i=((n%l)+l)%l)=>A.slice(i).concat(A.slice(0,i))

EDIT1::*
Branchless, mutationless implementation.

So hey, turns out I had a branch where I didn’t need it. Here is a working solution.
negative num = right rotate by |num|
positive num = left rotate by num

function r(A,n,l=A.length) {
  return A.map((x,i,a) => A((((n+i)%l) + l) % l))
}

The equation ((n%l) + l) % l maps exactly positive and negative numbers of any arbitrarily large values of n

ORIGINAL

Rotate left and right. Rotate left with positive n, rotate right with negative n.

Works for obscenely large inputs of n.

No mutation mode. Too much mutation in these answers.

Also, fewer operations than most answers. No pop, no push, no splice, no shift.

const rotate = (A, num ) => {
   return A.map((x,i,a) => {
      const n = num + i
      return n < 0 
        ? A((((n % A.length) + A.length) % A.length))
        : n < A.length 
        ? A(n) 
        : A(n % A.length)
   })
}

or

 const rotate = (A, num) => A.map((x,i,a, n = num + i) => 
  n < 0
    ? A((((n % A.length) + A.length) % A.length))
    : n < A.length 
    ? A(n) 
    : A(n % A.length))

//test
rotate((...Array(5000).keys()),4101)   //left rotation
rotate((...Array(5000).keys()),-4101000)  //right rotation, num is negative

// will print the first index of the array having been rotated by -i
// demonstrating that the rotation works as intended
(...Array(5000).keys()).forEach((x,i,a) => {
   console.log(rotate(a,-i)(0))
}) 
// prints even numbers twice by rotating the array by i * 2 and getting the first value
//demonstrates the propper mapping of positive number rotation when out of range
(...Array(5000).keys()).forEach((x,i,a) => {
   console.log(rotate(a,i*2)(0))
})

Explanation:

map each index of A to the value at index offset. In this case

offset = num

if the offset < 0 then offset + index + positive length of A will point to the inverse offset.

if offset > 0 and offset < length of A then simply map the current index to the offset index of A.

Otherwise, modulo the offset and the length to map the offset in the bounds of the array.

Take for instance offset = 4 and offset = -4.

When offset = -4, and A = (1,2,3,4,5), for each index, offset + index will make the magnitude (or Math.abs(offset)) smaller.

Let’s explain the calculation for the index of negative n first. A((((n % A.length) + A.length) % A.length)+0) and been intimidated. Don’t be. It took me 3 minutes in a Repl to work it out.

  1. We know n is negative because the case is n < 0. If the number is larger than the range of the Array, n % A.length will map it into the range.
  2. n + A.length add that number to A.length to offset n the correct
    amount.
  3. We know n is negative because the case is n < 0. n + A.length add that number to A.length to offset n the correct amount.
  4. Next Map it to the range of the length of A using modulo. The second modulous is necessary to map the result of the calculation into an indexable range

    enter image description here

  5. First index: -4 + 0 = -4. A.length = 5. A.length – 4 = 1. A2 is 2. Map index 0 to 2. (2,... )

  6. Next index, -4 + 1 = -3. 5 + -3 = 2. A2 is 3. Map index 1 to 3. (2,3... )
  7. Etc.

The same process applies to offset = 4.
When offset = -4, and A = (1,2,3,4,5), for each index, offset + index will make the magnitude bigger.

  1. 4 + 0 = 0. Map A(0) to the value at A(4). (5...)
  2. 4 + 1 = 5, 5 is out of bounds when indexing, so map A2 to the
    value at the remainder of 5 / 5, which is 0. A2 = value at
    A(0). (5,1...)
  3. repeat.

rotation – Rotate & Translate a MatrixTRS

Hello I have a question about translation & rotation of a MatrixTRS…

So basicly I have a given MatrixTRS A in space, define by a positionA, rotationA and scaleA.
(DISCLAIMER: I am using Unity, but I do not use Transform, therefore I have a Matrix4x4, created like that:
Matrix4x4 A = Matrix4x4.TRS(position, rotation, scale);

Ok, Now I have a Point in space, with a given rotation, named PositionB, and RotationB.
I would like to translate & Rotate my TRS matrix to that positionB, and rotationB.

I know I have to do something like b.transform.TransformPoint() and Quaternion.Inverse(b.transform.rotation)*a.transform.rotation, but i didn’t manage to make it right yet.

Thanks!

display – How to rotate the touch input on an external touchscreen connected to a Macbook Pro?

I am trying to connect an external touchscreen to a Macbook Pro (Mid 2015, macOS Mojave version 10.14.6). The touch input and the screen works, but by default the orientation of both of them is vertical. I need them to be horizontal.

I can easily change the orientation of the screen (following the steps described here), but while the screen is rotated, the touch input stays vertical – so e.g. when I swipe left to right, the cursor moves up-down.

I tried searching any mentions of similar problems and I went through all preferences, but I could not find anything related to my issue. Anyone experienced something similar?

FWIW, I am connecting the screen using hdmi, and the touch input is connected via USB.

macos – Rotate PDF in Safari

If it’s mis-oriented in Safari that means the original is formatted that way. Safari only provides a “quick viewer” of sorts for PDF files and is only rendering what was provided.

What you need to do is open it in Preview.

enter image description here

Simply right click anywhere on the PDF in Safari and select “Open With Preview.” Once you’re in Preview, you can rotate the PDF with ⌘ CommandL or ⌘ CommandR to rotate left and right respectively.

unity – How to rotate velocity Vector3 to always point the same direction so that it can be applied to 2d blendtree?

Given two variables, a Vector3 representing body velocity and a Quaternion representing body’s local rotation, how could I normalize the velocity vector so that it’s always oriented towards the default Vector3.forward direction?

The context of this problem is that I have a 2D blendtree for character movement animations. I wanted to use the RigidBody.velocity to control the two blendtree axes. This did not work as I initially expected because, depending on body rotation, the velocity also rotates to that direction and this when I’m moving forwards but my body is rotated 90 degrees to the right, my right (x) velocity would be 10 and my forward (z) velocity would be 0. In that case I would like to, using the current body rotation and velocity values, “normalize” the given velocity vector so that it has 10 in forward (z) velocity and 0 in right (x) velocity any time the entity is moving forward, no matter it’s orientation.

I’ve tried playing with Vector3.RotateTowards and Quaternion.LookRotation but I haven’t gotten the desired results and I don’t really know what to look for.