cocos2dx 学习笔记之摄像头与3D精灵的移动

----------基于cocos2dx 3.9 + cocos studio 2.3.3.0 + VS2015测试

一、关于世界摄像头,如果你不知道该如何设置,下面的几种方式可选其一:

  1 第三人称视角(多数2D~3D游戏中,摄像头跟随主角形式),初始化时,斜向下45°取景,此时不要调用lookat:

auto camera = Camera::createPerspective(60.0, (float)winSize.width / winSize.height, 1, 1000);
_camera->setRotation3D(Vec3(-45, 0, 0));

 在场景的更新中,不断更新位置(跟随人物),放置在人物的斜上方(一般来说高度由Y决定,前后距离由Z决定): 

//update camera's position
_camera->setPosition3D(_orc->getPosition3D() + camera_offset);

2 如果是第一人称视角,则需要将camera挂在主角身上:初始化之后挂载到人物上

auto _camera = Camera::createPerspective(60, (float)winSize.width / winSize.height, 1, 500);
_camera->setPosition3D(Vec3(0, 1, 0));
_camera->lookAt(Vec3(0, 0, 1));
_orc->addChild(_camera);
 之后再场景切换中,不断设置摄像机的位置以及观察点: 

_camera->setPosition3D(Vec3(0, 1, 0));
_camera->lookAt(_orc->getPosition3D() + Vec3(0, 0, 1), Vec3(0.0f, 1.0f, 0.0f));//第二个参数可省略,此为默认值,观察物体正前方
最后,camera有个setCameraFlag属性值,在3D世界中,所有需要被观察的物体都需要通过setCameraMask的mask值与flag做与操作,如果不为0,则表示受此摄像机观察,如果你不想写的这么麻烦,或者怕漏掉,可以直接在所有3D元素的基层layer中最后调用一次就好,一般如下:

_layer3D = Layer::create();
addChild(_layer3D);
//初始化摄像机 
//初始化UI
//初始化世界对象...
//通过_layer3D->addChild将所有node添加到地图
//最后
_layer3D->setCameraMask(2);//具体的值根据实际情况而定
=============================分割线=============================

// MARK: Camera 位于cocos/2d/CCNode.cpp中,看到就明白了,第二个参数默认为true
void Node::setCameraMask(unsigned short mask, bool applyChildren)
{
    _cameraMask = mask;
    if (applyChildren)
    {
        for (const auto& child : _children)
        {
            child->setCameraMask(mask, applyChildren);
        }
    }
}

如果你想通过前后左右来移动镜头:

void HelloWorld::onTouchesMoved(const std::vector<Touch*>& touchs, Event * event)
{
	//log("call onTouchesMoved");
	//推进角度
	/*if (!touchs.empty()) {
		Point touch = touchs[0]->getPreviousLocation() - touchs[0]->getLocation();
		_distanceZ -= touch.y * 0.1f;
		updateCameraTransform();
	}*/
	//自由角度
	if (touchs.size() == 1) {
		Point newPos = touchs[0]->getPreviousLocation() - touchs[0]->getLocation();
		Vec3 cameraPos = _camera->getPosition3D();
		cam
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值