简体   繁体   中英

How can I write this C# Z-axis vector rotation in JavaScript?

I have written a very simple XNA game in C# that uses the following method to rotationally alter projectiles as they fly towards a target. The objective of this is to make the projectiles somewhat 'homing':

float rotation;
Vector2 velocity;
int speed;

public void SetRotation(float value) // Make the projectiles homing
{
    rotation = value;

    velocity = Vector2.Transform(new Vector2(0, -speed),
            Matrix.CreateRotationZ(rotation));
}

I am trying (for my own learning purposes - I am very new to JavaScript) to port my game to JavaScript and allow it to be played inside a canvas. Could anyone suggest how I could re-write the above method as a JS function?

As someone who is a complete beginner to JavaScript would this most easily be done using an existing framework of some kind?

The method of rotating a vector involves some basic matrix math. (Please forgive the ASCII art. No LaTeX makes this more difficult)

First represent the vector in homogenous-coordinate form:

    [ x ]
v = | y |
    | z |
    [ 1 ]

The rotation matrix is provided by:

    [ cos(r)  -sin(r)  0  0 ]
M = | sin(r)   cos(r)  0  0 |
    |  0        0      1  0 |
    [  0        0      1  1 ]

Where r is the amount of rotation about Z

To apply the transformation, multiply the matrix M by the vector v :

          [ cos(r)  -sin(r)  0  0 ]   [ x ]
v' = Mv = | sin(r)   cos(r)  0  0 | * | y |
          |  0        0      1  0 |   | z |
          [  0        0      0  1 ]   [ 1 ]

Simplifying the multiplication gives the formula

v' = { x' = x * cos(r) - y * sin(r)
     { y' = x * sin(r) + y * cos(r)
     { z' = z

(Note: in Javascript, the sin() and cos() functions take arguments in radians.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM