当前位置:网站首页>Cocos creator direction and angle conversion

Cocos creator direction and angle conversion

2022-07-07 14:28:00 Snail games

1、 Let an object move in his direction

cc.Node Node rotation It's an angle , therefore , In order to achieve this goal , First of all, according to rotation Find out his dir Direction , It's easy to do. . Sample code :

update(dt){
        // because Math The function accepts solitude , So we first convert the rotation of nodes into radians
        var angle = this.node.rotation / 180 * Math.PI;
        // Synthesis based on X The direction vector in the positive direction
        var dir = cc.v2(Math.cos(angle),Math.sin(angle));
        // Unit vector
        dir.normalizeSelf();

        // Move the position according to the direction vector
        var moveSpeed = 100;
        this.node.x += dt * dir.x * moveSpeed;
        this.node.y += dt * dir.y * moveSpeed;

}

2、 Make one object face another

Through high school mathematics, we can know , A To B Vector = B spot - A spot . Then we just need to set the location of the target object - My place , You can get the direction vector .

The direction vector is converted to an angle , We need to recognize an implicit variable , The benchmark of this angle is X Affirmative direction . Using vectors to represent is (1,0).

cc.Vec2 Two functions are provided cc.Vec2.angle and cc.Vec2.signAngle, Compared with the former , The angle produced by the latter is symbolic , The former will always be positive . We use cc.Vec2.signAngle To convert the direction vector into radians . See the code for details .

function lookAtObj(target){
        // Calculate the orientation
        var dx = target.x - this.node.x;
        var dy = target.y - this.node.y;
        var dir = cc.v2(dx,dy);

        // Calculate the included angle radian according to the orientation
        var angle = dir.signAngle(cc.v2(1,0));

        // Convert radians into Euler angles
        var degree = angle / Math.PI * 180;

        // Assign to node
        this.node.rotation = degree;

}

原网站

版权声明
本文为[Snail games]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130614387063.html