cocos2d-xcocos2d-js

Rotate node to look at another node


Cocos Creator - I have a node that I want to rotate towards another node, here is the code I'm using:

update: function (dt) {
    this.rotate();
},

rotate: function () {
    var diff =  this.target.position - this.node.position;
    var angle = Math.atan2(diff.x, diff.y);
    this.node.rotation = cc.radiansToDegress(angle);
},

But it's not rotating at all, I tried to search the docs but couldn't find anything helpful.


Solution

  • var diff =  this.target.position - this.node.position;
    

    You're basically trying to subtract an object from an object. Check

    {'x':2, 'y':3} - {'x':4, 'y':6} 
    

    in your JS console. The result is NaN You need to subtract each dimension manually.

    var diff = {
    'x' : this.target.position.x - this.node.position.x,
    'y':this.target.position.y - this.node.position.y 
    };