cocos2d 确定用户触摸屏幕上的位置

发布于 2024-10-07 02:03:50 字数 595 浏览 1 评论 0原文

我试图使用 cocos2d 精灵确定用户相对于屏幕上的字符触摸的位置。当用户单击精灵的左侧时,我希望精灵向左运行,反之亦然。 我的问题是,当用户单击一侧并移动到另一侧而不放开触摸时(cctouchend不会触发),精灵会继续运行,但面向错误的方向。我将在哪里实施检查(以及如何)来确定用户的触摸是否已移至角色的另一侧?

我尝试过的当前代码:

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView: [touch view]];  
    CGPoint moveDifference = ccpSub(touchLocation, _character.position);
    if (moveDifference.x < 0) {
      _character.flipX = YES;
    } else {
      _character.flipX = NO;
    }   
}

谢谢。

I am trying to determine where the user is touching in relation to the character on the screen using cocos2d sprites. When the user clicks to the left of the sprite, I want the sprite to run to the left, and vice versa.
My problem is, when the user clicks on one side and moves over to the other side without letting go of the touch (cctouchended doesnt fire), the sprite keeps running, but facing the wrong direction. Where would I implement the check (and how) to determine if the user's touch has moved to the other side of the character?

current code that I tried:

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView: [touch view]];  
    CGPoint moveDifference = ccpSub(touchLocation, _character.position);
    if (moveDifference.x < 0) {
      _character.flipX = YES;
    } else {
      _character.flipX = NO;
    }   
}

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

流心雨 2024-10-14 02:03:50

您需要像这样转换您的触摸位置。

CGPoint location = [touch locationInView: [touch view]];    
location = [[CCDirector sharedDirector] convertToGL: location];

然后你就可以在 cocos2d 中的视图上获得正确的触摸位置。

You need to convert Your touch location like this.

CGPoint location = [touch locationInView: [touch view]];    
location = [[CCDirector sharedDirector] convertToGL: location];

Then you get correct touch location on your view in cocos2d.

权谋诡计 2024-10-14 02:03:50

你不能把它放在 ccTouchesBegan 中吗?这样就可以解决问题了,我想...

Can't you just put it in ccTouchesBegan instead? That would solve it, I think...

吾性傲以野 2024-10-14 02:03:50

您必须记下您当前的位置,并使用此函数 ccp(location.x, location.y) 您可以将精灵移动到您想要的方向

You have to note your current location , and using this function ccp(location.x, location.y) you can move your sprite in that direction in which you want

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文