cocos2d-x 物理世界与spine骨骼的运用

2023-11-15

Head

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"
#include "spine/spine.h"

#include "E:\tesetspine\cocos2d\external\Box2D\Dynamics\b2World.h"
#include "E:\tesetspine\cocos2d\cocos\editor-support\spine\SkeletonAnimation.h"

USING_NS_CC;

using namespace spine;

class HelloWorld : public cocos2d::Layer ,public b2ContactListener
{
public:
    static cocos2d::Scene* createScene();

    virtual bool init();
    
    // a selector callback
    void menuCloseCallback(cocos2d::Ref* pSender);
    
    // implement the "static create()" method manually
    CREATE_FUNC(HelloWorld);
	void InitSpine();
	void InitWorld();
	void initPhysics();

	static cocos2d::CCScene* scene();  

	// 重写生命周期函数  
	virtual void onEnter();  
	virtual void onEnterTransitionDidFinish();  
	virtual void onExit();  

	// 重写CCTargetTouchDelegate  
	virtual bool onTouchBegan(CCTouch *pTouch, CCEvent *pEvent);  
	virtual void onTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
	virtual void onTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
	virtual void onTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);

	// 重写update回调函数  
	virtual void update(float delta);  

	// 重写Bos2D监听函数  
	virtual void BeginContact(b2Contact* contact);  
private:  
	b2World *world;  
	b2Body* groundBody;  
	void addNewSpriteAtPosition(CCPoint &pt);  

};

#endif // __HELLOWORLD_SCENE_H__


Cpp

#include "HelloWorldScene.h"
#include "Box2D\Box2D.h"
USING_NS_CC;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

void HelloWorld::InitWorld()
{

}

// on "init" you need to initialize your instance
void HelloWorld::InitSpine()
{
	// create menu, it's an autorelease object
	auto skeletonNode = new SkeletonAnimation("spineboy.json", "spineboy.atlas");
	skeletonNode->setMix("walk", "attack", 0.2f);
	skeletonNode->setMix("jump", "walk", 0.4f);

	for (int i = 0; i < 100; i++)
	{
		i % 2 == 0 ? skeletonNode->addAnimation(0, "walk", false) : skeletonNode->addAnimation(0, "jump", false);
	}
	skeletonNode->setDebugBonesEnabled(false);
	skeletonNode->setDebugSlotsEnabled(true);

	Size windowSize = Director::getInstance()->getVisibleSize();
	skeletonNode->setPosition(windowSize.width / 2, windowSize.height / 2);
	skeletonNode->setScale(0.1f);
	addChild(skeletonNode);
}

bool HelloWorld::init()
{
    //
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

	// 初始化物理引擎  
	auto listener = EventListenerTouchOneByOne::create();
	listener->setSwallowTouches(true);
	listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
	listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
	//开始游戏循环  
	this->scheduleUpdate();

    /
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object

    /
    // 3. add your codes below...

    // add a label shows "Hello World"
	CCSprite *sprite = CCSprite::create("HelloWorld.png");
	sprite->setPosition(ccp(visibleSize.width / 2.0, visibleSize.height / 2.0));
	this->addChild(sprite);
    // create and initialize a label
	initPhysics();
	InitWorld();
	InitSpine();
    return true;
}


void HelloWorld::initPhysics()
{
	CCSize winSize = CCDirector::sharedDirector()->getVisibleSize();

	//重力参数  
	b2Vec2 gravity;
	gravity.Set(0.0f, -10.0f);
	//创建世界  
	world = new b2World(gravity);
	// 允许物体是否休眠  
	world->SetAllowSleeping(true);
	// 开启连续物理测试  
	world->SetContinuousPhysics(true);

	// 设置物理碰撞的监听代理  
	world->SetContactListener(this);

	//地面物体定义  
	b2BodyDef groundBodyDef;
	// 左下角  
	groundBodyDef.position.Set(winSize.width / 2.0 / 32, winSize.height / 2.0 / 32);
	// 设置为静态物体  
	groundBodyDef.type = b2_staticBody;

	// 创建地面物体  
	groundBody = world->CreateBody(&groundBodyDef);

	// 定义一个有边的形状  
	b2PolygonShape groundBox;

	// 底部  
	groundBox.SetAsBox(winSize.width / 2 / 32, 0, b2Vec2(0, -winSize.height / 2 / 32), 0);
	//使用夹具固定形状到物体上  
	groundBody->CreateFixture(&groundBox, 0);

	// 顶部  
	groundBox.SetAsBox(winSize.width / 2 / 32, 0, b2Vec2(0, winSize.height / 2 / 32), 0);
	groundBody->CreateFixture(&groundBox, 0);

	// 左边  
	groundBox.SetAsBox(0, winSize.height / 2 / 32, b2Vec2(-winSize.width / 2 / 32, 0), 0);
	groundBody->CreateFixture(&groundBox, 0);

	// 右边  
	groundBox.SetAsBox(0, winSize.height / 2 / 32, b2Vec2(winSize.width / 2 / 32, 0), 0);
	groundBody->CreateFixture(&groundBox, 0);
}

void HelloWorld::addNewSpriteAtPosition(CCPoint &pt)
{
	CCLOG("Add sprite x:%0.2f y:%02.f", pt.x, pt.y);

	//创建物理引擎精灵对象  
	CCSprite *sprite = CCSprite::create("BoxA.png");
	sprite->setPosition(pt);
	this->addChild(sprite);

	float sprWidth = sprite->getContentSize().width;
	float spriHeight = sprite->getContentSize().height;

	//物体定义  
	b2BodyDef bodyDef;
	bodyDef.type = b2_dynamicBody;
	bodyDef.position.Set(pt.x / 32, pt.y / 32);
	bodyDef.userData = sprite;

	b2Body *body = world->CreateBody(&bodyDef);
	// 定义2米见方的盒子形状  
	b2PolygonShape dynamicBox;
	// 注意这里的宽度和高度都是精灵的一半再除以PTM_RATIO  
	dynamicBox.SetAsBox(sprWidth / 2 / 32, spriHeight / 2 / 32);

	// 夹具定义  
	b2FixtureDef fixtureDef;
	//设置夹具的形状  
	fixtureDef.shape = &dynamicBox;
	//设置密度  
	fixtureDef.density = 1.0f;
	//设置摩擦系数  
	fixtureDef.friction = 0.3f;
	//设置弹力系数  
	fixtureDef.restitution = 0.5f;
	//使用夹具固定形状到物体上    
	body->CreateFixture(&fixtureDef);
}

void HelloWorld::update(float delta)
{
	world->Step(delta, 8, 3);

	for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
	{
		if (b->GetType() == b2_dynamicBody)
		{
			if (b->GetUserData() != NULL)
			{
				CCSprite* sprite = (CCSprite*)b->GetUserData();
				sprite->setPositionY(b->GetPosition().y * 32);
				sprite->setRotation(-1 * CC_RADIANS_TO_DEGREES(b->GetAngle()));
			}
		}
	}
}

void HelloWorld::BeginContact(b2Contact* contact)
{
	if (contact->GetFixtureA()->GetBody() == groundBody || contact->GetFixtureB()->GetBody() == groundBody)
	{
		CCLOG("检测到物理碰撞");
	}
}

void HelloWorld::onEnter()
{
	CCLOG("HelloWorld::onEnter");
	CCLayer::onEnter();
}

void HelloWorld::onEnterTransitionDidFinish()
{
	CCLOG("HelloWorld::onEnterTransitionDidFinish");
	CCLayer::onEnterTransitionDidFinish();
}

void HelloWorld::onExit()
{
	CCLOG("HelloWorld::onExit");
	CCLayer::onExit();
}

bool HelloWorld::onTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
	CCPoint pt = pTouch->getLocation();
	this->addNewSpriteAtPosition(pt);
	return true;
}

void HelloWorld::onTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
}

void HelloWorld::onTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
}

void HelloWorld::onTouchCancelled(CCTouch *pTouch, CCEvent *pEvent)
{

}

void HelloWorld::menuCloseCallback(Ref* pSender)
{
    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

cocos2d-x 物理世界与spine骨骼的运用 的相关文章

随机推荐

  • sklearn 神经网络

    sklearn 神经网络 url https blog csdn net luanpeng825485697 article details 79064657 url sklearn 神经网络 多层感知器的优点 可以学习得到非线性模型 使用
  • 雷军发布会刚结束,就能写出上万字原创文章!

    前言 看完雷军演讲会之后你有没有看到过很多文章 成千上万个字的原创文章 瞬间就出现了 这是一个一个字敲的吗 当然不是 是AI 话不多说直接上教程 把雷军的演讲整理到笔记中 可以是md格式 word格式等等 复制粘贴即可 打开网站 smart
  • vmware workstation14连网

    记录一下手残的过程 1 选择NAT形式的连接 2 在桌面的右上角有个圆圈 右击这个图标 会显示一个有线连接 默认是关闭的 3 所以设置成连接状态 4 右击有线连接 进行网络配置 5 所有都配置成自动获取
  • MybatisPlus多表连接查询

    mybatis plus作为mybatis的增强工具 它的出现极大的简化了开发中的数据库操作 但是长久以来 它的联表查询能力一直被大家所诟病 一旦遇到left join或right join的左右连接 你还是得老老实实的打开xml文件 手写
  • mybatis与数据库连接过程

    菜鸟发文 请大神多多指导 1 准被一个maven项目 2 先导入jar包 3 配置mybatis核心文件 4 把连接数据库的配置项抽离出来 5 编写实体类 6 编写接口 7 编写mapper映射文件 8 把相同SQL session 方法抽
  • TCP三次握手-backlog队列问题

    TCP三次握手 backlog队列问题 md 概述 之前有同事做压力测试时 发现无论如何都无法突破128并发的问题 经排查发现该服务器ACCEPT QUEUE队列都为128 限制了网络的并发 TCP三次握手 Linux内核协议栈为一个TCP
  • 初识-常见浏览器兼容性问题与解决方案

    浏览器兼容问题一 不同浏览器的标签默认的外补丁和内补丁不同 问题症状 随便写几个标签 不加样式控制的情况下 各自的margin 和padding差异较大 碰到频率 100 解决方案 CSS里 margin 0 padding 0 备注 这个
  • 前后端利用accessToken与refreshToken无感刷新

    项目初衷 以jwt 由header payload和signature组成 为例 用户登录成功 后端返回accessToken 前端保存 请求接口携带 一切都是水到渠成的 可是在acessToken失效时 你正好请求一次接口 接口就挂了 可
  • SpringBoot集成ShedLock分布式定时任务

    文章目录 前言 一 背景 二 ShedLock是什么 三 落地实现 1 1 引入依赖包 1 2 配置数据库连接信息 1 3 创建Mysql数据表 1 4 配置LockProvider 1 5 创建定时Job 四 结果分析 前言 一 背景 在
  • 【性能测试】Jmeter —— jmeter计数器

    jmeter计数器 如果需要引用的数据量较大 且要求不能重复或者需要递增 那么可以使用计数器来实现 如 新增功能 要求名称不能重复 1 新增计数器 计数器 允许用户创建一个在线程组之内都可以被引用的计数器 计数器允许用户配置一个起点 一个最
  • 《Go语言在微服务中的崛起:为什么Go是下一个后端之星?》

    博主猫头虎 带您进入 Golang 语言的新世界 博客首页 猫头虎的博客 面试题大全专栏 文章图文并茂 生动形象 简单易学 欢迎大家来踩踩 IDEA开发秘籍专栏 学会IDEA常用操作 工作效率翻倍 100天精通Golang 基础入门篇 学会
  • c语言 常量表达式,Constant expressions(常量表达)

    几种表达式被称为常量表达式 预处理器常量表达式 if 或 elif 后面的表达式必须扩展为 除赋值 增量 减量 函数调用或逗号之外的其他操作符 其参数是预处理常量表达式 整数常量 字符常量 特殊的预处理器操作员 defined 当在 if表
  • 面试题 : Top-k问题

    目录 简介 题目 示例 提示 开始解题 1 思路 2 解题代码 3 时间复杂度 4 运行结果 编辑 目前问题 真正的解法 1 以找前K个最大的元素为例 2 代码执行过程 时间复杂度的计算 3 画图演示代码执行过程 4 解题代码 两种解法的比
  • webpack3 配置详解

    今天详细的学习了webpack3 下面贴出我的主要配置代码给后来人一些参考 Created by shanpengfei051 on 2018 1 3 const path require path const uglify require
  • H264编码原理(I帧B帧P帧)

    I帧B帧P帧 编码帧的分类 I帧 intraframe frame 关键帧 采用帧内压缩技术 IDR帧属于I帧 每个GOP组中第一帧肯定是I帧 而且还是一种特殊的I帧 也可以称为IDR帧 一个GOP中可能有很多I帧 但是只有一个IDR帧 如
  • MySQL 行转列 列转行

    转载 mysql 行转列 列转行 行转列 准备数据 CREATE TABLE tb score id INT 11 NOT NULL auto increment userid VARCHAR 20 NOT NULL COMMENT 用户i
  • centos7安装apache

    centos7安装apache 第一步 检查是否有旧版本的apache 有就卸载 rpm qa grep httpd 因为我没有 就没有卸载的动作 第二步 安装apache yum install httpd 默认yes 可以添加参数 y
  • Linux环境下安装ssh2模块

    环境 Linux环境 Centos or RedHat 1 确认环境已安装php 5 rpm qa grep php 5 php 5 3 3 48 el6 8 x86 64 2 安装ssh2所依赖的rpm包如下图灰色部分显示 安装顺序可以按
  • Less-22 Cookie Injection- Error Based- Double Quotes - string (基于错误的双引号字符型Cookie注入)

    这关和上一关类似 只不过把单引号注入改成了双引号 看题目 尝试取消报错 成功 发现and后面的条件真假回显会不同 所以我们同样有很多的方法去注入 详见第二十关 这里我们使用联合查询 其他方法自行进行解码 很简单 结束
  • cocos2d-x 物理世界与spine骨骼的运用

    Head ifndef HELLOWORLD SCENE H define HELLOWORLD SCENE H include cocos2d h include spine spine h include E tesetspine co