简体   繁体   English

如何在JavaScript中编写C#Z轴矢量旋转?

[英]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. 我已经用C#编写了一个非常简单的XNA游戏,该游戏使用以下方法在弹丸飞向目标时旋转改变弹丸。 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. 我正在尝试(出于我自己的学习目的-我对JavaScript非常陌生)将我的游戏移植到JavaScript并允许它在画布中播放。 Could anyone suggest how I could re-write the above method as a JS function? 谁能建议我如何将上述方法重写为JS函数?

As someone who is a complete beginner to JavaScript would this most easily be done using an existing framework of some kind? 作为JavaScript的完整入门者,使用现有的某种框架最容易做到这一点吗?

The method of rotating a vector involves some basic matrix math. 旋转向量的方法涉及一些基本矩阵数学。 (Please forgive the ASCII art. No LaTeX makes this more difficult) (请原谅ASCII文字。没有LaTeX会使这更加困难)

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 其中r是绕Z的旋转量

To apply the transformation, multiply the matrix M by the vector v : 要应用转换,请将矩阵M乘以向量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.) (注意:在Javascript中, sin()cos()函数采用弧度表示参数。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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