How to get correct vector for cursorPosition in Scenes that follow sprite

How to get correct vector for cursorPosition in Scenes that follow sprite

Hi, I have a Scene that follows to a sprite (player) by using:

auto followTheSprite = Follow::create(m_box, Rect::ZERO);

that’s work fine, I also want the rotation of sprite point to mouse cursor, then I’ve added
an EventListenerMouse by:

auto mouseListener = EventListenerMouse::create();
mouseListener->onMouseMove = CC_CALLBACK_1(HelloWorld::onMouseMove, this);

in my HelloWorld::onMouseMove i wrote this

void HelloWorld::onMouseMove(cocos2d::Event* event){
	if (m_box) {
		EventMouse* mouseEvent = (EventMouse*)event;
		cocos2d::Vec2 tankPosition = m_box->getPosition();
		cocos2d::Vec2 cursorPosition = mouseEvent->getLocation();
		Vec2 diff = cursorPosition - tankPosition;
		float angle = atan2f(diff.y, diff.x)*(180/3.1416);

this doesn’t work fine, at firts when the game is launched de initial point of my sprite is (640, 480), at this point the cursorPosition , it show me correct values to my opinion, I mean, the values range look fit the screen size :smiley: and the orientation of my sprite, point to mouse cursor, such as I spect, but, when the sprite start to move through the world, and it got away from start point, the sprite doesn’t point to cursor, and the values that I got from cursor are not sense for me, I should spect similar values to tankPosition but a got values like start lauch values, what I can think is, the values of cursor are relative to screen and not to the world, but I’m not sure if that’s right, and I’ve attempting to use Director::getInstance()->ConverteToGL(cursorPosition) , but the values I got are similar to cursorPosition without use ConverteToGL.

Have you tried auto mouseLocationInView = mouseEvent->getLocationInView(); ?

You also want to compare when both positions are in the same coord. space, so you may need to convert into tank’s node space … tank->convertToNodeSpace(mouseLocationInView); or possibly tank’s parent’s node space (which is probably HelloWorld scene in this case so might also just use this with this->convertToNodeSpace(...).

Thanks for you answer, it was very helpfull to me.

 auto mouseLocationInView = mouseEvent->getLocationInView();

And in addition to:

Vec2 tank = convertToWindowSpace(m_box->getPosition());

make my code works such I spect, but, this carry a little problem that is

float angle = atan2f(diff2.y, diff2.x) * (180 / 3.1416);

the angle getting from above line is in inverse value, so I solve this by multiply by -1

		m_box->setRotation(angle*-1  + 90);

the 90 is just a angle offset desired to my sprite. Thanks by your help.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.