1. 程式人生 > >6.Libgdx擴充套件學習之Box2D_滑鼠關節

6.Libgdx擴充套件學習之Box2D_滑鼠關節

下面一些內容定義來自《Box2D中文手冊》

關於

關節用於把物體約束到世界,或約束到其它物體上。在遊戲中,典型例子有木偶,蹺蹺板和滑輪。用不同的方式將關節結合起來使用,可以創造出有趣的運動。
有些關節提供了限制(limit),使可以控制運動的範圍。有些關節還提供了馬達(motor),它可以以指定的速度驅動關節一直運動,直到你指定了更大的力或扭矩來抵消這種運動。
關節馬達有許多不同的用途。可以使用關節來控制位置,只要提供一個與目標之距離成正比例的關節速度即可。還可以模擬關節摩擦:將關節速度置零,並且提供一個小的、但有效的最大力或扭矩;那麼馬達就會努力保持關節不動,直到負載變得過大為止。

關節定義

每種關節型別都有各自的定義(definition),它們都派生自 JointDef。所有的關節都連線兩個不同的物體,其中一個物體有可能是靜態的。關節也可以連線兩個 static 或者 kinematic 型別的物體,但這沒有任何實際用途,只會浪費處理器時間。
可以為任何一種關節型別指定使用者資料。還可以提供一個標記,用於防止用關節相連的物體之間發生碰撞。實際上, 這是預設行為。也可以通過設定 collideConnected,來允許相連的物體之間發生碰撞
很多關節定義需要提供一些幾何資料。一個關節常常需要一個錨點(anchor point)來定義,這是固定於相接物體中的點。 Box2D 要求這些點在區域性座標系中指定,這樣,即便當前物體的變化違反了關節約束(joint constraint),關節還是可以被指定–這通常會發生在遊戲儲存或載入進度時。
另外,有些關節定義需要知道物體之間預設的相對角度。這樣才能正確地約束旋轉。
初始化幾何資料可能有些乏味。所以很多關節提供了初始化函式,使用當前的物體的形狀,來消除大部分工作。然而,這些初始化函式通常只應用於原型,在產品程式碼中應該直接地定義幾何資料。這能使關節行為更具健壯性。

滑鼠關節

滑鼠關節用於通過滑鼠來操控物體,它試圖將物體託向當前滑鼠游標的位置,而在旋轉方面就沒有限制。
滑鼠關節的定義需要一個目標點(target point),最大力(maximum force),頻率(frequency),阻尼率(damping ratio)。目標點最開始與物體的錨點重合,最大力用於防止再多個動態物體相互作用時的激烈反應。頻率和阻尼用於創造一種彈性效果。
1.com.badlogic.gdx.physics.box2d.JointDef

    /** The first attached body. **/
    public Body bodyA = null
; /** The second attached body **/ public Body bodyB = null; /** Set this flag to true if the attached bodies should collide. **/ public boolean collideConnected = false;

2.com.badlogic.gdx.physics.box2d.joints.MouseJointDef

    /** The initial world target point. This is assumed to coincide with the body anchor initially.   錨點  */
    public final Vector2 target = new Vector2();

    /** The maximum constraint force that can be exerted to move the candidate body. Usually you will express as some multiple of
     * the weight (multiplier * mass * gravity). */
    public float maxForce = 0;

    /** The response speed. */
    public float frequencyHz = 5.0f;

    /** The damping ratio. 0 = no damping, 1 = critical damping. */
    public float dampingRatio = 0.7f;

3.com.badlogic.gdx.physics.box2d.joints.MouseJoint extends Joint
/** A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force.
** This allows the constraint to stretch and without applying huge forces. NOTE: this joint is not documented in the manual
* because it was developed to be used in the testbed. If you want to learn how to use the mouse joint, look at the testbed. /

![這裡寫圖片描述](http://img.blog.csdn.net/20170105225558705?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvenFpYW5nXzU1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
/**
 * 滑鼠關節測試
 */
public class MouseJointTest extends ApplicationAdapter {

    World world;
    Box2DDebugRenderer box2DDebugRenderer;
    Body mouseJointBody, groundBody;
    Fixture fixture;

    OrthographicCamera camera;
    Vector3 point = new Vector3();

    float scene_width = 12.8f;
    float scene_height = 7.2f;
    Vector2 target = new Vector2();

    @Override
    public void create() {
        world = new World(new Vector2(0.0f, -9.8f), true);
        box2DDebugRenderer = new Box2DDebugRenderer();

        camera = new OrthographicCamera(scene_width, scene_height);
        camera.position.set(scene_width / 2, scene_height / 2, 0);
        camera.update();

        groundBody = createGroundWall();

        Gdx.input.setInputProcessor(new HandA());

        BodyDef bodyDef = new BodyDef();
        bodyDef.position.set(3.0f, 4.8f);
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        mouseJointBody = world.createBody(bodyDef);

        PolygonShape polygonShape = new PolygonShape();
        polygonShape.setAsBox(0.5f, 0.5f);

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = polygonShape;
        fixtureDef.density = 1.0f;
        fixtureDef.restitution = 0.6f;

        fixture = mouseJointBody.createFixture(fixtureDef);
    }

    @Override
    public void render() {
        world.step(1 / 60f, 6, 2);

        Gdx.gl.glClearColor(0.39f, 0.58f, 0.92f, 1.0f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        box2DDebugRenderer.render(world, camera.combined);
    }

    @Override
    public void dispose() {
        world.dispose();
        box2DDebugRenderer.dispose();
    }

    public Body createGroundWall() {
        BodyDef bodyDef = new BodyDef();
        bodyDef.position.set(scene_width * 0.5f, 0.2f);
        Body body1 = world.createBody(bodyDef);

        PolygonShape polygonShape = new PolygonShape();
        polygonShape.setAsBox(scene_width * 0.5f, 0.2f);
        body1.createFixture(polygonShape, 0.0f);

        bodyDef.position.set(0.4f, scene_height * 0.5f);
        Body body2 = world.createBody(bodyDef);

        polygonShape.setAsBox(0.2f, scene_height * 0.5f);
        body2.createFixture(polygonShape, 0);

        bodyDef.position.set(12.4f, scene_height * 0.5f);
        Body body3 = world.createBody(bodyDef);

        polygonShape.setAsBox(0.2f, scene_height * 0.5f);
        body3.createFixture(polygonShape, 0);

        bodyDef.position.set(scene_width * 0.5f, 7.0f);
        Body body4 = world.createBody(bodyDef);

        polygonShape.setAsBox(scene_width * 0.5f, 0.2f);
        body4.createFixture(polygonShape, 0);
        polygonShape.dispose();

        return body1;
    }

    private void logInfo(String message) {
        Gdx.app.log("MouseJointTest", message);
    }

    class HandA extends InputAdapter {

        MouseJoint mouseJoint;

        @Override
        public boolean touchDragged(int screenX, int screenY, int pointer) {
            logInfo("touchDragged");
            if (mouseJoint != null) {
                camera.unproject(point.set(screenX, screenY, 0));
                mouseJoint.setTarget(target.set(point.x, point.y));
            }

            return false;
        }

        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            logInfo("touchDown");
            camera.unproject(point.set(screenX, screenY, 0));
            //  當滑鼠點選到物體時才會建立滑鼠關節,並繫結
            if (fixture.testPoint(point.x, point.y)) {
                if (mouseJointBody == null) return false;

                MouseJointDef mouseJointDef = new MouseJointDef();
                mouseJointDef.bodyA = groundBody;
                mouseJointDef.bodyB = mouseJointBody;
                mouseJointDef.collideConnected = true;
                mouseJointDef.target.set(point.x, point.y);
                mouseJointDef.maxForce = 1000.0f * mouseJointBody.getMass();

                mouseJoint = (MouseJoint) world.createJoint(mouseJointDef);
                mouseJointBody.setAwake(true);

            }
            return false;
        }

        @Override
        public boolean touchUp(int screenX, int screenY, int pointer, int button) {
            logInfo("touchUp");
            // 滑鼠關節,不再使用時要銷燬
            if (mouseJoint != null) {
                world.destroyJoint(mouseJoint);
                mouseJoint = null;
            }
            return false;
        }
    }
}

相關推薦

6.Libgdx擴充套件學習Box2D_滑鼠關節

下面一些內容定義來自《Box2D中文手冊》 關於 關節用於把物體約束到世界,或約束到其它物體上。在遊戲中,典型例子有木偶,蹺蹺板和滑輪。用不同的方式將關節結合起來使用,可以創造出有趣的運動。 有些關節提供了限制(limit),使可以控制運動的範

7.Libgdx擴充套件學習Box2D_距離關節 旋轉關節

文章中的概念來自《Box2D》中文手冊 上一節中我們介紹了關節和滑鼠關節的使用方法,本章中我們繼續介紹距離關節和旋轉關節 距離關節(DistanceJoint) 距離關節是兩個物體上各有一點,兩點之間的距離必須固定不變。當指定一個距離關節時,兩

2.Libgdx擴充套件學習Box2D_剛體和形狀

文章中涉及的很多概念,都是來自《Box2D中文手冊》。有統一的解釋方便理解。 物體(剛體/Body) 概念介紹 物體具有位置和速度。可以將力(forces)、扭矩(torques)、衝量(impulses)應用到物體上。 物體可以是靜態

3.Libgdx擴充套件學習Box2D_夾具

文章中涉及的很多概念,都是來自《Box2D中文手冊》。有統一的解釋方便理解 夾具 概念介紹 形狀不知道物體的存在,並可獨立於物理模擬而被使用。因此 Box2D 提供 Fixture 類,用於將形狀附加到物體上。一個物體可以有零個或多個

6、MongoDB學習主從復制

ges 方式 blog for data- director 分享 .com 復制 環境: 主:127.0.0.1:27017 從:127.0.0.1:27018 一、主庫添加配置文件(master = true) port = 27017 dbpath = /data

6.最俗學習-Vue原始碼學習-資料篇(上)

原始碼地址 這篇重點學習Vue的資料響應系統,檔案路徑src/core/instance // expose real self vm._self = vm initLifecycle(vm) initEvents(vm) callHook(vm, '

es6學習路(6):陣列的擴充套件

1. Array.from() Array.from方法用於將兩類物件轉為真正的陣列:類似陣列的物件( array-like object )和可遍歷( iterable )的物件(包括 ES6 新增的資料結構 Set 和 Map )。 下面是一個類似陣列的物件,Array

Python學習6?函數,遞歸,內置函數

erro memory 子程序 none 種類 lan 萬年 字典 得到 一python中的函數 函數是邏輯結構化和過程化的一種編程方法。 python中函數定義方法: def test(x): "The function definitions" x

FPGA小白學習路(6)串口波特率問題的處理

失真 https 容易 由於 間隔 之路 使用 應該 增強 串口波特率問題的處理 此博文一共包含三個方面的內容:(1)異步串口通信的數據格式;(2)為何串口通信中接收端采樣時鐘頻率是傳輸的波特率的16倍;(3)串口波特率等概念。 1、異步串口通信的數據格式   串口的通信可

java學習旅-6

自增 tro pri 只需要 循環嵌套 java 問題 定義 一次 有關for循環嵌套問題的優化: for(int i = 0;i < 1000;i ++) { for(int j = 0;j < 100;j ++) {

Python學習路—2018/6/14

使用 響應 瀏覽器 con 限制 end F12 spa TP Python學習之路—2018/6/14 1.瀏覽器與服務器 瀏覽器向服務器發送請求的過程為請求過程,服務器向瀏覽器響應的過程為響應過程。 2.簡單的web應用程序 import socket sock =

Python學習路—2018/6/26

添加記錄 decimal sin 單表 IT S3 src 壞蛋 char Python學習之路—2018/6/26 1.ORM 單表操作 刪除與修改記錄 >>> ret = Book.objects.filter(title="go").delete()

Python3學習路~6.2 實例演示面向對象編程的好處

之路 %s python 哈哈 對象 name 面向 lex 我們 首先建一個dog類,實例化為3個dog對象,並讓它們都叫。 class Dog: def bulk(self): print("xiaohuang:wang wang wa

Oracle菜鳥學習在RedHat 6.5上安裝Oracle

ola 信息 nis lease run log version ora- 修改配置文件 Oracle菜鳥學習之在RedHat 6.5上安裝Oracle 11G 首發:http://www.arppinging.com/wordpress/?p=90 安裝前準備工作 上

三十一、python學習Flask框架(三)檢視:路由、上下文、Flask-Script擴充套件

一、裝飾器路由的具體實現 1.Flask框架路由實現 Flask有兩大核心:Werkzeug和Jinja2 Werkzeug實現路由、除錯和Web伺服器閘道器介面 Jinja2實現了模板。 Werkzeug是一個遵循WSGI協議的python函式庫

C++基礎學習物件和類(6)

物件和類 主要內容: 面向物件程式設計與過程性程式設計 類的定義和實現 公有類和私有類 類的資料成員 類方法 建立和使用類物件 類的建構函式和解構函式 const成員函式 this指標 建立物件陣列 類作用域

pyhon學習selenium模擬滑鼠事件

 首先我們貼程式碼,原始碼解析好吧。 # Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE fil

機器學習python基礎篇6

“”" @theme list的取值,增加,刪除 @time 2018/11/26 @author lz “”" name_list=[“zhangsan”,“lisi”,“maliu”];#定義列表 name_list[0]=“張三”#修改列表的值 name_list.pop()#在末尾刪

React學習擴充套件效能分析工具-Perf(二十八)

                     import Perf from 'react-addons-perf' // ES6語法var Perf = require('react-addons-perf') // ES5語法針對nodejsvar Perf = React.addons.Perf; //

React學習擴充套件不變的資料(immutability-helper)優化(三十二)

                       注意  引入import update from 'react-addons-update'; // ES6var update = require('react-addons-update'); // ES5 with npmvar update = React