如何抓取 b2Body 并在屏幕上移动它?(cocos2d,box2d,iphone)

How to grab a b2Body and move it around the screen? (cocos2d,box2d,iphone)(如何抓取 b2Body 并在屏幕上移动它?(cocos2d,box2d,iphone))

本文介绍了如何抓取 b2Body 并在屏幕上移动它?(cocos2d,box2d,iphone)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在屏幕上移动任何在屏幕上触摸的 b2body.我听说过一些关于鼠标关节的事情..

I want to move any b2body that is touched on the screen around the screen. I've heard something about mouse joints..

我发现:http://iphonedev.net/2009/08/05/how-to-grab-a-sprite-with-cocos2d-and-box2d/

但是如果我只是将 ccTouch 方法复制到一个新项目中(当然还有标题中的变量),我只会给我很多错误.例如.world->查询 <- 未找到成员

but I just gives me a lot of errors if i just copy the ccTouch Methods into a new project (of course the variables in the header too). E.g. world->Query <- NO MEMBER FOUND

愿有人制作一个 tut/一个新项目并将其上传到这里.还是有更好的办法?

May someone make a tut/a new project and upload it here. Or is there a better way?

推荐答案

首先你要创建 b2QueryCallback 子类:

First you have to create b2QueryCallback subclass:

class QueryCallback : public b2QueryCallback
{
public:
    QueryCallback(const b2Vec2& point)
    {
        m_point = point;
        m_object = nil;
    }

    bool ReportFixture(b2Fixture* fixture)
    {
        if (fixture->IsSensor()) return true; //ignore sensors

        bool inside = fixture->TestPoint(m_point);
        if (inside)
        {
             // We are done, terminate the query.
             m_object = fixture->GetBody();
                 return false;
        }

        // Continue the query.
        return true;
    }

    b2Vec2  m_point;
    b2Body* m_object;
};

然后在你的 touchBegan 方法中:

Then in your touchBegan method:

    b2Vec2 pos = yourTouchPos;
// Make a small box.
b2AABB aabb;
b2Vec2 d;
d.Set(0.001f, 0.001f);
aabb.lowerBound = pos - d;
aabb.upperBound = pos + d;

// Query the world for overlapping shapes.
QueryCallback callback(pos);
world_->QueryAABB(&callback, aabb);         

b2Body *body = callback.m_object;
if (body)
    {
        //pick the body
    }

我认为您可以通过两种方式控制拾取的身体.第一个,正如您所注意到的 - 创建一个 mouseJoint,第二个是使您的身体运动并控制它的速度(而不是位置! - 它会在碰撞时提供非物理行为,因为速度将为零).在第一种情况下,如果您非常快速地移动对象,则移动时会有一些延迟.我自己没有尝试第二种方式,因为在这种情况下,身体不会与其他运动和静态物体发生碰撞.

There are two ways I see you can control the picked body. The first one, as you notices - to create a mouseJoint and the second is to make your body kinematic and control it's velocity (not position! - it will provide non-physical behavior when collide because the speed will be zero). In first case if you will move your objects very fast there will be some delay when moving. I did not try the second way myself because in this case the body will not collide with other kinematic and static bodies.

此外,您可能希望在移动时锁定身体的旋转.

Also you may want to lock body's rotation when moving.

这篇关于如何抓取 b2Body 并在屏幕上移动它?(cocos2d,box2d,iphone)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何抓取 b2Body 并在屏幕上移动它?(cocos2d,box2d,iphone)

基础教程推荐