Пример #1
0
 void Sphere::getNormal (const Point& point, Vector &normalAtPoint) const
 {
   normalAtPoint = point.diff(getPosition());
   normalAtPoint.normalize();
 }
Пример #2
0
void Platform::hit(EventCollision *p_c)
{
	if (((p_c->getObject1()->getType()) == "Hero") ||
		((p_c->getObject2()->getType()) == "Hero"))
	{
		auto heroPtr = (Object*)nullptr;
		auto platformPtr = (Object*)nullptr;
		if ((p_c->getObject1()->getType()) == "Hero")
		{
			heroPtr = p_c->getObject1();
			platformPtr = p_c->getObject2();
		}
		else
		{
			heroPtr = p_c->getObject2();
			platformPtr = p_c->getObject1();

		}
		WorldManager &world_manager = WorldManager::getInstance();
		auto heroPos = heroPtr->getPosition();
		auto platformPos = platformPtr->getPosition();
		int xOffset = 0;
		int yOffset = 0;
		if (heroPtr->getPosition().getY() <= (this->getPosition().getY() + this->getHeight()))
		{
			if (getXVelocity() > 0)
			{
				xOffset = this->lastXDisplacement;
			}
			else if (getXVelocity() < 0)
			{
				xOffset = this->lastXDisplacement;
			}
		}

		if (getYVelocity() > 0)
		{
			//only adjust hero position when platform goes up
			//yOffset = 1;
		}
		else if (getYVelocity() < 0)
		{
			yOffset = this->lastYDisplacement;
		}
		float xCD;
		float yCD;
		bool xChanged;
		if (xOffset || yOffset)
		{
			heroPos = Position(heroPos.getX(), heroPos.getY());
			platformPos = Position(platformPos.getX(), platformPos.getY());
			xCD = platformPtr->getXVelocityCountdown();
			xChanged = xCD > prevXCD;
			yCD = platformPtr->getYVelocityCountdown();

			heroPos.setX(heroPos.getX() + xOffset);
			platformPos.setX(platformPos.getX());
			if (!xChanged)
			{
				heroPos.setX(heroPos.getX() - xOffset);
				//platformPos.setX(platformPos.getX() - xOffset);
			}
			prevXCD = xCD;

			if (yCD <= 0)
			{
				heroPos.setY(heroPos.getY() + yOffset);
				platformPos.setY(platformPos.getY() + yOffset);
			}
		}
		if (yOffset > 0)
		{
			world_manager.moveObject(platformPtr, platformPos);
			world_manager.moveObject(heroPtr, heroPos);
		}
		else if (yOffset < 0)
		{
			ObjectList list = world_manager.isCollision(heroPtr, heroPos);
			if (!list.isEmpty())
			{
				world_manager.markForDelete(heroPtr);
			}
			else
			{
				world_manager.moveObject(heroPtr, heroPos);
				world_manager.moveObject(platformPtr, platformPos);
			}
		}

		if (xOffset)
		{
			ObjectList list = world_manager.isCollision(heroPtr, heroPos);
			if (list.isEmpty())
			{
				world_manager.moveObject(heroPtr, heroPos);
				world_manager.moveObject(platformPtr, platformPos);
			}
			else
			{
				world_manager.moveObject(platformPtr, platformPos);
				list = world_manager.isCollision(heroPtr, heroPos);
				if (list.isEmpty())
				{
					world_manager.moveObject(heroPtr, heroPos);

				}
				else
				{
					//world_manager.markForDelete(heroPtr);
				}
			}
		}
	}
	else
	{
		// monster, trap, etc. will stop the platform completely
		//setXVelocityCountdown(getXVelocityCountdown() + fabs(getXVelocity()));
		//setYVelocityCountdown(getYVelocityCountdown() + fabs(getYVelocity()));
	}

}
Пример #3
0
void CharacterObject::updateCharacter(float dt)
{
	/*
	 * You can fire weapons while moving
	 *
	 * Two Modes: Moving and Action
	 * Moving covers walking & jumping
	 * Action covers complex things like shooting, entering vehicles etc.
	 *
	 * Movement animation should be handled here
	 *  If Current weapon is one handed, then it can be used while walking.
	 *  This means blending the weapon animation with the walk animation.
	 *  No weapons can be used while sprinting.
	 *  Need an "aim vector" to apply torso correction.
	 *
	 *  If movement vector is less than some threshold, fully walk animation
	 *  (time adjusted for velocity).
	 */

	if(physCharacter) {
		glm::vec3 walkDir = updateMovementAnimation(dt);

		position = getPosition();

		if (canTurn()) {
			rotation = glm::angleAxis(m_look.x, glm::vec3{0.f, 0.f, 1.f});
		}

		walkDir = rotation * walkDir;

		if( jumped )
		{
			if( !isOnGround() )
			{
				walkDir = rotation * glm::vec3(0.f, jumpSpeed * dt, 0.f);
			}
		}

		if (isAlive())
		{
			physCharacter->setWalkDirection(btVector3(walkDir.x, walkDir.y, walkDir.z));
		}
		else
		{
			physCharacter->setWalkDirection(btVector3(0.f, 0.f, 0.f));
		}

		auto Pos = physCharacter->getGhostObject()->getWorldTransform().getOrigin();
		position = glm::vec3(Pos.x(), Pos.y(), Pos.z());

		// Handle above waist height water.
		auto wi = engine->data->getWaterIndexAt(getPosition());
		if( wi != NO_WATER_INDEX ) {
			float wh = engine->data->waterHeights[wi];
			auto ws = getPosition();
			wh += engine->data->getWaveHeightAt(ws);
			
			// If Not in water before
			//  If last position was above water
			//   Now Underwater
			//  Else Not Underwater
			// Else
			//  Underwater
			
			if( ! inWater && ws.z < wh && _lastHeight > wh ) {
				ws.z = wh;

				btVector3 bpos(ws.x, ws.y, ws.z);
				physCharacter->warp(bpos);
				auto& wt = physObject->getWorldTransform();
				wt.setOrigin(bpos);
				physObject->setWorldTransform(wt);

				physCharacter->setGravity(0.f);
				inWater = true;
			}
			else {
				physCharacter->setGravity(9.81f);
				inWater = false;
			}
		}
		_lastHeight = getPosition().z;
	}
	else
	{
		updateMovementAnimation(dt);
	}
}
Пример #4
0
void EnemyShip::setSpawnPosition(vec3 position)
{
    m_position = position;
    spawnpos = getPosition();
}
Пример #5
0
void KeyboardPaddle::move(float delta) {
        // TODO: Change to setPositionY()
        setPosition(40, getPosition().y + _offset);
}
Пример #6
0
void PhysicsGeom::changed(ConstFieldMaskArg whichField, 
                            UInt32            origin,
                            BitVector         details)
{
    Inherited::changed(whichField, origin, details);

    //Do not respond to changes that have a Sync origin
    if(origin & ChangedOrigin::Sync)
    {
        return;
    }

    if(whichField & BodyFieldMask)
    {
        if(getBody() != NULL)
        {
	        dGeomSetBody(_GeomID, getBody()->getBodyID());
        }
        else
        {
	        dGeomSetBody(_GeomID, 0);
        }
    }
    if(whichField & PositionFieldMask)
    {
	    dGeomSetPosition(_GeomID, getPosition().x(),getPosition().y(),getPosition().z());
    }
    if(whichField & RotationFieldMask)
    {
	    dMatrix3 rotation;
	    Vec4f v1 =  getRotation()[0];
	    Vec4f v2 =  getRotation()[1];
	    Vec4f v3 =  getRotation()[2];
	    rotation[0]   = v1.x();
	    rotation[1]   = v1.y();
	    rotation[2]   = v1.z();
	    rotation[3]   = 0;
	    rotation[4]   = v2.x();
	    rotation[5]   = v2.y();
	    rotation[6]   = v2.z();
	    rotation[7]   = 0;
	    rotation[8]   = v3.x();
	    rotation[9]   = v3.y();
	    rotation[10]  = v3.z();
	    rotation[11]  = 0;
	    dGeomSetRotation(_GeomID, rotation);
    }
    if(whichField & QuaternionFieldMask)
    {
	    dQuaternion q;
	    q[0]=getQuaternion().w();
	    q[1]=getQuaternion().x();
	    q[2]=getQuaternion().y();
	    q[3]=getQuaternion().z();
	    dGeomSetQuaternion(_GeomID,q);
    }
    if(whichField & OffsetPositionFieldMask &&
        getBody() != NULL)
    {
	    dGeomSetOffsetPosition(_GeomID, getOffsetPosition().x(),getOffsetPosition().y(),getOffsetPosition().z());
    }
    if(whichField & OffsetRotationFieldMask &&
        getBody() != NULL)
    {
	    dMatrix3 rotation;
	    Vec4f v1 =  getOffsetRotation()[0];
	    Vec4f v2 =  getOffsetRotation()[1];
	    Vec4f v3 =  getOffsetRotation()[2];
	    rotation[0]   = v1.x();
	    rotation[1]   = v1.y();
	    rotation[2]   = v1.z();
	    rotation[3]   = 0;
	    rotation[4]   = v2.x();
	    rotation[5]   = v2.y();
	    rotation[6]   = v2.z();
	    rotation[7]   = 0;
	    rotation[8]   = v3.x();
	    rotation[9]   = v3.y();
	    rotation[10]  = v3.z();
	    rotation[11]  = 0;
	    dGeomSetOffsetRotation(_GeomID, rotation);
    }
    if(whichField & OffsetQuaternionFieldMask && getBody() != NULL)
    {
	    dQuaternion q;
	    q[0]=getOffsetQuaternion().w();
	    q[1]=getOffsetQuaternion().x();
	    q[2]=getOffsetQuaternion().y();
	    q[3]=getOffsetQuaternion().z();
	    dGeomSetOffsetQuaternion(_GeomID,q);
    }
    if(whichField & CategoryBitsFieldMask)
    {
	    dGeomSetCategoryBits(_GeomID, getCategoryBits());
    }
    if(whichField & CollideBitsFieldMask)
    {
	    dGeomSetCollideBits(_GeomID, getCollideBits());
    }
    if(whichField & SpaceFieldMask)
    {
        dSpaceID CurSpace(dGeomGetSpace(_GeomID));
     
        if(CurSpace != 0 &&
           (getSpace() == NULL ||
            CurSpace != getSpace()->getSpaceID()))
        {
            dSpaceRemove(CurSpace,_GeomID);
        }

        if(getSpace() != NULL)
        {
	        dSpaceAdd(getSpace()->getSpaceID(), _GeomID);
        }
    }
    if(whichField & EnableFieldMask)
    {
        if(getEnable())
        {
            dGeomEnable(_GeomID);
        }
        else
        {
            dGeomDisable(_GeomID);
        }
    }
}
Пример #7
0
void MonsterTortoise::checkPosSchedule()
{
	Vec2 newPos = getPosition();
	b2Body * body = getBody();
	b2Vec2 oldVelocity = body->GetLinearVelocity();
	if (newPos.x - m_lastPos.x >= -0.01f && newPos.x - m_lastPos.x <= 0.01f)
	{
		//转向处理
		if (!m_bIsDefend || (m_bIsDefend && m_bIsRoll))
		{
			changeVelocityDirection();
		}
	}
	else
	{
		if (m_bLeft)
		{
			if (!m_bIsDefend)
				body->SetLinearVelocity(b2Vec2(-MMSpeed_Tortoise, oldVelocity.y));
			//else if (oldVelocity.x < -0.00001f)
			//	getBody()->SetLinearVelocity(b2Vec2(-MMSpeed_TortoiseDefense, oldVelocity.y));
		}
		else
		{
			if (!m_bIsDefend)
				body->SetLinearVelocity(b2Vec2(MMSpeed_Tortoise, oldVelocity.y));
			//else if (oldVelocity.x > 0.00001f)
			//	getBody()->SetLinearVelocity(b2Vec2(MMSpeed_TortoiseDefense, oldVelocity.y));
		}
	}

	////防守非滚动状态x轴速度更改
	//if (m_bIsDefend && !m_bIsRoll && (oldVelocity.x < -0.00001f || oldVelocity.x > 0.00001f))
	//{
	//	body->SetAwake(false);
	//	body->SetLinearVelocity(b2Vec2(0.0f, oldVelocity.y));
	//}
	m_lastPos.set(newPos);

	//空中校验,是否踩着物体,光线投射
	if (!m_bIsDefend)
	{
		m_bStepObject = false;
		float fPtm = getPTMRatio();
		b2Vec2 beginPoint1(newPos.x / fPtm, newPos.y / fPtm);	//投射起点
		b2Vec2 endPoint1(beginPoint1.x, beginPoint1.y - getContentSize().height / fPtm);	//投射终点
		b2World * pWorld = GameScene::getInstance()->getWorld();
		pWorld->RayCast(this, beginPoint1, endPoint1);
		if (!m_bStepObject)
		{
			//由于可能透过细小缝隙,故而执行二次投射
			b2Vec2 beginPoint2(beginPoint1.x + (m_bLeft ? -1 : 1) * getContentSize().width / 4 / fPtm, beginPoint1.y);
			b2Vec2 endPoint2(beginPoint2.x, endPoint1.y);
			pWorld->RayCast(this, beginPoint2, endPoint2);
		}

		if (!m_bStepObject)
		{
			//再走将会掉下,掉头
			changeVelocityDirection();
		}
	}
}
Пример #8
0
void OSGObjectBase::setWorldPosition(osg::Vec3 targ)
{
    osg::Vec3 p_w = getWorldPosition();
    osg::Vec3 diff = targ-p_w;
    setPosition(getPosition()+diff);
}
Пример #9
0
void CtrlList::handleEvent( EvtGeneric &rEvent )
{
    if( rEvent.getAsString().find( "key:down" ) != std::string::npos )
    {
        int key = ((EvtKey&)rEvent).getKey();
        VarList::Iterator it = m_rList.begin();
        bool previousWasSelected = false;
        while( it != m_rList.end() )
        {
            VarList::Iterator next = it;
            ++next;
            if( key == KEY_UP )
            {
                // Scroll up one item
                if( it != m_rList.begin() || &*it != m_pLastSelected )
                {
                    bool nextWasSelected = ( &*next == m_pLastSelected );
                    (*it).m_selected = nextWasSelected;
                    if( nextWasSelected )
                    {
                        m_pLastSelected = &*it;
                    }
                }
            }
            else if( key == KEY_DOWN )
            {
                // Scroll down one item
                if( next != m_rList.end() || &*it != m_pLastSelected )
                {
                    (*it).m_selected = previousWasSelected;
                }
                if( previousWasSelected )
                {
                    m_pLastSelected = &*it;
                    previousWasSelected = false;
                }
                else
                {
                    previousWasSelected = ( &*it == m_pLastSelected );
                }
            }
            it = next;
        }

        // Redraw the control
        makeImage();
        notifyLayout();
    }

    else if( rEvent.getAsString().find( "mouse:left" ) != std::string::npos )
    {
        EvtMouse &rEvtMouse = (EvtMouse&)rEvent;
        const Position *pos = getPosition();
        int yPos = m_lastPos + ( rEvtMouse.getYPos() - pos->getTop() ) /
            (m_rFont.getSize() + LINE_INTERVAL);
        VarList::Iterator it;
        int index = 0;

        if( rEvent.getAsString().find( "mouse:left:down:ctrl,shift" ) !=
                 std::string::npos )
        {
            // Flag to know if the current item must be selected
            bool select = false;
            for( it = m_rList.begin(); it != m_rList.end(); ++it )
            {
                bool nextSelect = select;
                if( index == yPos || &*it == m_pLastSelected )
                {
                    if( select )
                    {
                        nextSelect = false;
                    }
                    else
                    {
                        select = true;
                        nextSelect = true;
                    }
                }
                (*it).m_selected = (*it).m_selected || select;
                select = nextSelect;
                index++;
            }
        }

        else if( rEvent.getAsString().find( "mouse:left:down:ctrl" ) !=
                 std::string::npos )
        {
            for( it = m_rList.begin(); it != m_rList.end(); ++it )
            {
                if( index == yPos )
                {
                    (*it).m_selected = ! (*it).m_selected;
                    m_pLastSelected = &*it;
                    break;
                }
                index++;
            }
        }

        else if( rEvent.getAsString().find( "mouse:left:down:shift" ) !=
                 std::string::npos )
        {
            // Flag to know if the current item must be selected
            bool select = false;
            for( it = m_rList.begin(); it != m_rList.end(); ++it )
            {
                bool nextSelect = select;
                if( index == yPos ||  &*it == m_pLastSelected )
                {
                    if( select )
                    {
                        nextSelect = false;
                    }
                    else
                    {
                        select = true;
                        nextSelect = true;
                    }
                }
                (*it).m_selected = select;
                select = nextSelect;
                index++;
            }
        }

        else if( rEvent.getAsString().find( "mouse:left:down" ) !=
                 std::string::npos )
        {
            for( it = m_rList.begin(); it != m_rList.end(); ++it )
            {
                if( index == yPos )
                {
                    (*it).m_selected = true;
                    m_pLastSelected = &*it;
                }
                else
                {
                    (*it).m_selected = false;
                }
                index++;
            }
        }

        else if( rEvent.getAsString().find( "mouse:left:dblclick" ) !=
                 std::string::npos )
        {
            for( it = m_rList.begin(); it != m_rList.end(); ++it )
            {
                if( index == yPos )
                {
                    (*it).m_selected = true;
                    m_pLastSelected = &*it;
                    // Execute the action associated to this item
                    m_rList.action( &*it );
                }
                else
                {
                    (*it).m_selected = false;
                }
                index++;
            }
        }

        // Redraw the control
        makeImage();
        notifyLayout();
    }

    else if( rEvent.getAsString().find( "scroll" ) != std::string::npos )
    {
        int direction = ((EvtScroll&)rEvent).getDirection();

        double percentage = m_rList.getPositionVar().get();
        double step = 2.0 / (double)m_rList.size();
        if( direction == EvtScroll::kUp )
        {
            percentage += step;
        }
        else
        {
            percentage -= step;
        }
        m_rList.getPositionVar().set( percentage );
    }
}
Пример #10
0
Enemy::Enemy(const Enemy& enemy) : GameObject("enemy")
{
	m_bullets = enemy.m_bullets;
	delete m_collider;
	m_collider = new Collider(&(getPosition()), getTextureRect().width / 2.0f);
}
Пример #11
0
void Enemy::Hit(GameObject* other)
{
	if(other->m_collider->IsCircular)
	{
		if(other->GetType() != "Bullet")
		{
			sf::Vector2f normalizedDir = getPosition() - other->getPosition();
			float dist = MathHelper::Distance(getPosition(), other->getPosition());
			normalizedDir = MathHelper::Normalize(normalizedDir);
		
			move(normalizedDir * ((getTextureRect().width + other->getTextureRect().width) / 2.0f - dist));
		}
	}
	else
	{
		if(getPosition().x + m_collider->m_fRadius < other->getPosition().x - other->getTextureRect().width / 2)
		{
			float ownX = getPosition().x + m_collider->m_fRadius;
			float otherX = other->getPosition().x - other->getTextureRect().width / 2;
			move(otherX - ownX,0);
		}
		else if(getPosition().x - m_collider->m_fRadius > other->getPosition().x + other->getTextureRect().width / 2)
		{
			float ownX = getPosition().x - m_collider->m_fRadius;
			float otherX = other->getPosition().x + other->getTextureRect().width / 2;
			move(otherX - ownX,0);
		}

		if(getPosition().y - m_collider->m_fRadius < other->getPosition().y - other->getTextureRect().height / 2)
		{
			float ownY = getPosition().y + m_collider->m_fRadius;
			float otherY = other->getPosition().y - other->getTextureRect().height / 2;
			move(0, otherY - ownY);
		}
		else if(getPosition().y + m_collider->m_fRadius > other->getPosition().y + other->getTextureRect().height / 2)
		{
			float ownY = getPosition().y - m_collider->m_fRadius;
			float otherY = other->getPosition().y + other->getTextureRect().height / 2;
			move(0, otherY - ownY);
		}

		if(getPosition().y + m_collider->m_fRadius > other->getPosition().y - other->getTextureRect().height / 2 &&
		   getPosition().y - m_collider->m_fRadius < other->getPosition().y + other->getTextureRect().height / 2 &&
		   getPosition().x - m_collider->m_fRadius < other->getPosition().x + other->getTextureRect().width / 2 &&
		   getPosition().x + m_collider->m_fRadius > other->getPosition().x - other->getTextureRect().width / 2)
		{
			sf::Vector2f dir = MathHelper::Normalize(getPosition() - other->getPosition());
			move(dir * 10.0f);
		}
	}

	if(other->GetType() == "Bullet")
	{
		if(((Bullet*)(other))->m_owner != this)
		{
			m_fHealth -= 15;
			SoundManager::getInstance()->Play("impact_body", 70.f, true);
		}
	}
}
Пример #12
0
void BaseCar::update(float delta)
{
    _prePos = getPosition();
    Sprite::update(delta);
    FSM::update(delta);
}
Пример #13
0
void RenderableWebEntityItem::render(RenderArgs* args) {
    QOpenGLContext * currentContext = QOpenGLContext::currentContext();
    QSurface * currentSurface = currentContext->surface();
    if (!_webSurface) {
        _webSurface = new OffscreenQmlSurface();
        _webSurface->create(currentContext);
        _webSurface->setBaseUrl(QUrl::fromLocalFile(PathUtils::resourcesPath() + "/qml/"));
        _webSurface->load("WebEntity.qml");
        _webSurface->resume();
        _webSurface->getRootItem()->setProperty("url", _sourceUrl);
        _connection = QObject::connect(_webSurface, &OffscreenQmlSurface::textureUpdated, [&](GLuint textureId) {
            _webSurface->lockTexture(textureId);
            assert(!glGetError());
            // TODO change to atomic<GLuint>?
            withLock(_textureLock, [&] {
                std::swap(_texture, textureId);
            });
            if (textureId) {
                _webSurface->releaseTexture(textureId);
            }
            if (_texture) {
                _webSurface->makeCurrent();
                glBindTexture(GL_TEXTURE_2D, _texture);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
                glBindTexture(GL_TEXTURE_2D, 0);
                _webSurface->doneCurrent();
            }
        });

        auto forwardMouseEvent = [=](const RayToEntityIntersectionResult& intersection, const QMouseEvent* event, unsigned int deviceId) {
            // Ignore mouse interaction if we're locked
            if (this->getLocked()) {
                return;
            }

            if (event->button() == Qt::MouseButton::RightButton) {
                if (event->type() == QEvent::MouseButtonPress) {
                    const QMouseEvent* mouseEvent = static_cast<const QMouseEvent*>(event);
                    _lastPress = toGlm(mouseEvent->pos());
                }
            }

            if (intersection.entityID == getID()) {
                if (event->button() == Qt::MouseButton::RightButton) {
                    if (event->type() == QEvent::MouseButtonRelease) {
                        const QMouseEvent* mouseEvent = static_cast<const QMouseEvent*>(event);
                        ivec2 dist = glm::abs(toGlm(mouseEvent->pos()) - _lastPress);
                        if (!glm::any(glm::greaterThan(dist, ivec2(1)))) {
                            AbstractViewStateInterface::instance()->postLambdaEvent([this] {
                                QMetaObject::invokeMethod(_webSurface->getRootItem(), "goBack");
                            });
                        }
                        _lastPress = ivec2(INT_MIN);
                    }
                    return;
                }

                // FIXME doesn't work... double click events not received
                if (event->type() == QEvent::MouseButtonDblClick) {
                    AbstractViewStateInterface::instance()->postLambdaEvent([this] {
                        _webSurface->getRootItem()->setProperty("url", _sourceUrl);
                    });
                }

                if (event->button() == Qt::MouseButton::MiddleButton) {
                    if (event->type() == QEvent::MouseButtonRelease) {
                        AbstractViewStateInterface::instance()->postLambdaEvent([this] {
                            _webSurface->getRootItem()->setProperty("url", _sourceUrl);
                        });
                    }
                    return;
                }

                // Map the intersection point to an actual offscreen pixel
                glm::vec3 point = intersection.intersection;
                point -= getPosition();
                point = glm::inverse(getRotation()) * point;
                point /= getDimensions();
                point += 0.5f;
                point.y = 1.0f - point.y;
                point *= getDimensions() * METERS_TO_INCHES * DPI;
                // Forward the mouse event.  
                QMouseEvent mappedEvent(event->type(),
                    QPoint((int)point.x, (int)point.y),
                    event->screenPos(), event->button(),
                    event->buttons(), event->modifiers());
                QCoreApplication::sendEvent(_webSurface->getWindow(), &mappedEvent);
            }
        };

        EntityTreeRenderer* renderer = static_cast<EntityTreeRenderer*>(args->_renderer);
        QObject::connect(renderer, &EntityTreeRenderer::mousePressOnEntity, forwardMouseEvent);
        QObject::connect(renderer, &EntityTreeRenderer::mouseReleaseOnEntity, forwardMouseEvent);
        QObject::connect(renderer, &EntityTreeRenderer::mouseMoveOnEntity, forwardMouseEvent);
    }

    glm::vec2 dims = glm::vec2(getDimensions());
    dims *= METERS_TO_INCHES * DPI;
    // The offscreen surface is idempotent for resizes (bails early
    // if it's a no-op), so it's safe to just call resize every frame 
    // without worrying about excessive overhead.
    _webSurface->resize(QSize(dims.x, dims.y));
    currentContext->makeCurrent(currentSurface);

    PerformanceTimer perfTimer("RenderableWebEntityItem::render");
    Q_ASSERT(getType() == EntityTypes::Web);
    static const glm::vec2 texMin(0.0f), texMax(1.0f), topLeft(-0.5f), bottomRight(0.5f);

    Q_ASSERT(args->_batch);
    gpu::Batch& batch = *args->_batch;
    batch.setModelTransform(getTransformToCenter());
    bool textured = false, culled = false, emissive = false;
    if (_texture) {
        batch._glActiveTexture(GL_TEXTURE0);
        batch._glBindTexture(GL_TEXTURE_2D, _texture);
        textured = emissive = true;
    }
    
    DependencyManager::get<DeferredLightingEffect>()->bindSimpleProgram(batch, textured, culled, emissive);
    DependencyManager::get<GeometryCache>()->renderQuad(batch, topLeft, bottomRight, texMin, texMax, glm::vec4(1.0f));
}
Пример #14
0
void Character::update(sf::Time deltaTime)
{
    sf::Vector2f a(getPosition());
    sf::Vector2i position(efc::getCords(a));
    nextRedirect -= deltaTime.asSeconds();
    if (nextRedirect<0)
    {
        int number = rand() % 2;
        if ((currentAnimationIndex==efc::DIR_LEFT) || (currentAnimationIndex==efc::DIR_RIGHT))
        {
            if (number==0){
                setDirIndex(efc::DIR_DOWN);
                setDir();
            } else if (number==1)
            {
                setDirIndex(efc::DIR_UP);
                setDir();
            }
        } else if ((currentAnimationIndex==efc::DIR_UP) || (currentAnimationIndex==efc::DIR_DOWN))
        {
            if (number==0){
                setDirIndex(efc::DIR_LEFT);
                setDir();
            } else if (number==1)
            {
                setDirIndex(efc::DIR_RIGHT);
                setDir();
            }
        }

        nextRedirect = rand() % 4;

    }

    if (currentAnimationIndex==efc::DIR_UP)
    {
        if (position.y<2)
        {
            setDirIndex(efc::DIR_DOWN);
            setDir();
        }
    }  else   if (currentAnimationIndex==efc::DIR_DOWN)
    {
        if (position.y>efc::BOARD_SIZE-1)
        {
            setDirIndex(efc::DIR_UP);
            setDir();
        }
    } else   if (currentAnimationIndex==efc::DIR_LEFT)
    {

        if (position.x<2)
        {
            setDirIndex(efc::DIR_RIGHT);
            setDir();
        }
    }  else   if (currentAnimationIndex==efc::DIR_RIGHT)
    {
        if (position.x>efc::BOARD_SIZE-1)
        {
            setDirIndex(efc::DIR_LEFT);
            setDir();
        }
    }
    animatedSprite.update(deltaTime);

    if (active==true)
    {
        if (moveLeft>-1)
        {
//            sf::Vector2i cordsLeft(efc::transPosition(moveLeft));
            sf::Vector2i neededCords(efc::transPosition(moveLeft));

            sf::Vector2f newPos(efc::getScreenPos(neededCords));
            leftChar.setPosition(newPos.x+efc::TILE_SIZE/4,newPos.y);

            leftChar.move(202,76);
        }


        if (moveRight>-1)
        {
//            sf::Vector2i cordsRight(efc::transPosition(moveRight));
            sf::Vector2i neededCords(efc::transPosition(moveRight));

            sf::Vector2f newPos(efc::getScreenPos(neededCords));
            rightChar.setPosition(newPos.x+efc::TILE_SIZE/4,newPos.y);
            rightChar.move(202,76);

        }

//        std::cout << " dice " << diceResult<< moveLeft << " " << moveRight  << std::endl;
    }


}
bool CTimerControlApp::OnInit()
{
	SetVendorName(VENDOR_NAME);

	if (!wxApp::OnInit())
		return false;

	if (!m_nolog) {
		wxString logBaseName = LOG_BASE_NAME;
		if (!m_name.IsEmpty()) {
			logBaseName.Append(wxT("_"));
			logBaseName.Append(m_name);
		}

		if (m_logDir.IsEmpty())
			m_logDir = wxFileName::GetHomeDir();

		wxLog* log = new CLogger(m_logDir, logBaseName);
		wxLog::SetActiveTarget(log);
	} else {
		new wxLogNull;
	}

	m_config = new CTimerControlConfig(new wxConfig(APPLICATION_NAME), m_name);

	wxString frameName = APPLICATION_NAME + wxT(" - ");
	if (!m_name.IsEmpty()) {
		frameName.Append(m_name);
		frameName.Append(wxT(" - "));
	}
	frameName.Append(VERSION);

	if (!m_name.IsEmpty()) {
		wxString fileBase = SCHEDULE_BASE_NAME;
		fileBase.Append(wxT("_"));
		fileBase.Append(m_name);
		fileBase.Replace(wxT(" "), wxT("_"));

		wxFileName fileName(wxFileName::GetHomeDir(), fileBase, wxT("dat"));
		m_fileName = fileName.GetFullPath();
	} else {
		wxFileName fileName(wxFileName::GetHomeDir(), SCHEDULE_BASE_NAME, wxT("dat"));
		m_fileName = fileName.GetFullPath();
	}

	wxPoint position = wxDefaultPosition;

	int x, y;
	getPosition(x, y);
	if (x >= 0 && y >= 0)
		position = wxPoint(x, y);

	bool delay;
	getDelay(delay);

	m_frame = new CTimerControlFrame(frameName, position, delay);
	m_frame->Show();

	SetTopWindow(m_frame);

	wxLogInfo(wxT("Starting ") + APPLICATION_NAME + wxT(" - ") + VERSION);

	// Log the version of wxWidgets and the Operating System
	wxLogInfo(wxT("Using wxWidgets %d.%d.%d on %s"), wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER, ::wxGetOsDescription().c_str());

	createThread();

	return wxApp::OnInit();
}
Пример #16
0
void CtrlList::makeImage()
{
    delete m_pImage;

    // Get the size of the control
    const Position *pPos = getPosition();
    if( !pPos )
    {
        return;
    }
    int width = pPos->getWidth();
    int height = pPos->getHeight();
    int itemHeight = m_rFont.getSize() + LINE_INTERVAL;

    // Create an image
    OSFactory *pOsFactory = OSFactory::instance( getIntf() );
    m_pImage = pOsFactory->createOSGraphics( width, height );

    VarList::ConstIterator it = m_rList[m_lastPos];

    // Draw the background
    if( m_pBitmap )
    {
        // A background bitmap is given, so we scale it, ignoring the
        // background colors
        ScaledBitmap bmp( getIntf(), *m_pBitmap, width, height );
        m_pImage->drawBitmap( bmp, 0, 0 );

        // Take care of the selection color
        for( int yPos = 0; yPos < height; yPos += itemHeight )
        {
            int rectHeight = __MIN( itemHeight, height - yPos );
            if( it != m_rList.end() )
            {
                if( (*it).m_selected )
                {
                    m_pImage->fillRect( 0, yPos, width, rectHeight,
                                        m_selColor );
                }
                ++it;
            }
        }
    }
    else
    {
        // No background bitmap, so use the 2 background colors
        // Current background color
        uint32_t bgColor = m_bgColor1;
        for( int yPos = 0; yPos < height; yPos += itemHeight )
        {
            int rectHeight = __MIN( itemHeight, height - yPos );
            if( it != m_rList.end() )
            {
                uint32_t color = ( (*it).m_selected ? m_selColor : bgColor );
                m_pImage->fillRect( 0, yPos, width, rectHeight, color );
                ++it;
            }
            else
            {
                m_pImage->fillRect( 0, yPos, width, rectHeight, bgColor );
            }
            // Flip the background color
            bgColor = ( bgColor == m_bgColor1 ? m_bgColor2 : m_bgColor1 );
        }
    }

    // Draw the items
    int yPos = 0;
    for( it = m_rList[m_lastPos]; it != m_rList.end() && yPos < height; ++it )
    {
        UString *pStr = (UString*)(it->m_cString.get());
        uint32_t color = ( it->m_playing ? m_playColor : m_fgColor );

        // Draw the text
        GenericBitmap *pText = m_rFont.drawString( *pStr, color, width );
        if( !pText )
        {
            return;
        }
        yPos += itemHeight - pText->getHeight();
        int ySrc = 0;
        if( yPos < 0 )
        {
            ySrc = - yPos;
            yPos = 0;
        }
        int lineHeight = __MIN( pText->getHeight() - ySrc, height - yPos );
        m_pImage->drawBitmap( *pText, 0, ySrc, 0, yPos, pText->getWidth(),
                              lineHeight, true );
        yPos += (pText->getHeight() - ySrc );
        delete pText;

    }
}
void btMultiBodyJointLimitConstraint::createConstraintRows(btMultiBodyConstraintArray& constraintRows,
		btMultiBodyJacobianData& data,
		const btContactSolverInfo& infoGlobal)
{
	
    // only positions need to be updated -- data.m_jacobians and force
    // directions were set in the ctor and never change.

	if (m_numDofsFinalized != m_jacSizeBoth)
	{
        finalizeMultiDof();
	}


    // row 0: the lower bound
    setPosition(0, m_bodyA->getJointPos(m_linkA) - m_lowerBound);			//multidof: this is joint-type dependent

    // row 1: the upper bound
    setPosition(1, m_upperBound - m_bodyA->getJointPos(m_linkA));
	
	for (int row=0;row<getNumRows();row++)
	{
		
		btScalar direction = row? -1 : 1;

		btMultiBodySolverConstraint& constraintRow = constraintRows.expandNonInitializing();
        constraintRow.m_orgConstraint = this;
        constraintRow.m_orgDofIndex = row;
        
		constraintRow.m_multiBodyA = m_bodyA;
		constraintRow.m_multiBodyB = m_bodyB;
		const btScalar posError = 0;						//why assume it's zero?
		const btVector3 dummy(0, 0, 0);

		btScalar rel_vel = fillMultiBodyConstraint(constraintRow,data,jacobianA(row),jacobianB(row),dummy,dummy,dummy,dummy,posError,infoGlobal,0,m_maxAppliedImpulse);

		{
			//expect either prismatic or revolute joint type for now
			btAssert((m_bodyA->getLink(m_linkA).m_jointType == btMultibodyLink::eRevolute)||(m_bodyA->getLink(m_linkA).m_jointType == btMultibodyLink::ePrismatic));
			switch (m_bodyA->getLink(m_linkA).m_jointType)
			{
				case btMultibodyLink::eRevolute:
				{
					constraintRow.m_contactNormal1.setZero();
					constraintRow.m_contactNormal2.setZero();
					btVector3 revoluteAxisInWorld = direction*quatRotate(m_bodyA->getLink(m_linkA).m_cachedWorldTransform.getRotation(),m_bodyA->getLink(m_linkA).m_axes[0].m_topVec);
					constraintRow.m_relpos1CrossNormal=revoluteAxisInWorld;
					constraintRow.m_relpos2CrossNormal=-revoluteAxisInWorld;
					
					break;
				}
				case btMultibodyLink::ePrismatic:
				{
					btVector3 prismaticAxisInWorld = direction* quatRotate(m_bodyA->getLink(m_linkA).m_cachedWorldTransform.getRotation(),m_bodyA->getLink(m_linkA).m_axes[0].m_bottomVec);
					constraintRow.m_contactNormal1=prismaticAxisInWorld;
					constraintRow.m_contactNormal2=-prismaticAxisInWorld;
					constraintRow.m_relpos1CrossNormal.setZero();
					constraintRow.m_relpos2CrossNormal.setZero();
					
					break;
				}
				default:
				{
					btAssert(0);
				}
			};
			
		}

		{
			btScalar penetration = getPosition(row);
			btScalar positionalError = 0.f;
			btScalar	velocityError =  - rel_vel;// * damping;
			btScalar erp = infoGlobal.m_erp2;
			if (!infoGlobal.m_splitImpulse || (penetration > infoGlobal.m_splitImpulsePenetrationThreshold))
			{
				erp = infoGlobal.m_erp;
			}
			if (penetration>0)
			{
				positionalError = 0;
				velocityError = -penetration / infoGlobal.m_timeStep;
			} else
			{
				positionalError = -penetration * erp/infoGlobal.m_timeStep;
			}

			btScalar  penetrationImpulse = positionalError*constraintRow.m_jacDiagABInv;
			btScalar velocityImpulse = velocityError *constraintRow.m_jacDiagABInv;
			if (!infoGlobal.m_splitImpulse || (penetration > infoGlobal.m_splitImpulsePenetrationThreshold))
			{
				//combine position and velocity into rhs
				constraintRow.m_rhs = penetrationImpulse+velocityImpulse;
				constraintRow.m_rhsPenetration = 0.f;

			} else
			{
				//split position and velocity into rhs and m_rhsPenetration
				constraintRow.m_rhs = velocityImpulse;
				constraintRow.m_rhsPenetration = penetrationImpulse;
			}
		}
	}

}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Point origin = Director::getInstance()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.
    
    auto lbl_title = LabelTTF::create("じゃんけんゲーム", "HiraKakuProN-W6", 30);
    lbl_title->setPosition(Point(origin.x +visibleSize.width/2,
                                 origin.y +visibleSize.height - lbl_title->getContentSize().height ));
    this->addChild(lbl_title);
    
    // グーだけの単一スプライトを表示する
    jangken_aite = Sprite::create("goo.png");
    jangken_aite->setPosition(Point(origin.x+visibleSize.width/2,
                                    origin.y+visibleSize.height
                                    - lbl_title->getContentSize().height
                                    - jangken_aite->getContentSize().height
                                    -20));
    this->addChild(jangken_aite);
    
    // アニメーションを生成する
    auto jangken_anime = Animation::create();
    jangken_anime->addSpriteFrameWithFile("choki.png");
    jangken_anime->addSpriteFrameWithFile("par.png");
    jangken_anime->addSpriteFrameWithFile("goo.png");
    jangken_anime->setDelayPerUnit(0.1f);
    jangken_anime->setLoops(-1);
    jangken_anime->setRestoreOriginalFrame(true);
    jangken_anime_run = (CCAnimate*)CCSequence::create(
                                                CCAnimate::create(jangken_anime),
                                                NULL);
    // アニメーション実行
    jangken_aite->runAction(jangken_anime_run);
    
    
    
    // じゃんけんボタンを追加
    auto btn_goo = MenuItemImage::create("goo.png", "goo.png", CC_CALLBACK_1(HelloWorld::pushGoo, this));
    auto btn_choki = MenuItemImage::create("choki.png", "choki.png", CC_CALLBACK_1(HelloWorld::pushChoki, this));
    auto btn_par = MenuItemImage::create("par.png", "par.png", CC_CALLBACK_1(HelloWorld::pushPar, this));
    
    btn_goo->setPosition(Point(origin.x + btn_goo->getContentSize().width/2 + 10,
                               origin.y + visibleSize.height/2 - 20));
    
    btn_choki->setPosition(Point(btn_goo->getPosition().x + btn_choki->getContentSize().width + 10,
                               origin.y + visibleSize.height/2 - 20));
    
    btn_par->setPosition(Point(btn_choki->getPosition().x + btn_par->getContentSize().width + 10,
                               origin.y + visibleSize.height/2 - 20));
    
    
    auto btns = Menu::create(btn_goo, btn_choki, btn_par, NULL);
    btns->setPosition(Point::ZERO);
    this->addChild(btns);
    
    
    
    // 乱数を初期化
    srand((unsigned)time(NULL));
    
    lbl_dis = LabelTTF::create("", "HiraKakuProN-W6", 30);
    lbl_dis->setPosition(Point(origin.x + visibleSize.width/2,
                               origin.y + 200));
    addChild(lbl_dis);
    
    
    return true;
}
Пример #19
0
void MonsterTortoise::marioContact(MarioSprite * pMario)
{
	if (pMario == nullptr)
	{
		CC_ASSERT(false);
		return;
	}

	if (getMonsterStatus() == MonsterStatus_Invalid)
	{
		return;
	}
	else if (m_bIsDefend)
	{
		//重置弹力系数
		b2Fixture * fixture = getBody()->GetFixtureList();

		b2Vec2 oldVelocity = getBody()->GetLinearVelocity();
		enMarioStatus marioStatus = pMario->getMarioStatus();
		if (m_bIsRoll)
		{
			if (marioStatus == MarioSt_LJump || marioStatus == MarioSt_LDown ||
				marioStatus == MarioSt_RJump || marioStatus == MarioSt_RDown)
			{
				//马里奥空中状态,停止防守龟滚动
				getBody()->SetLinearVelocity(b2Vec2(0.0f, oldVelocity.y));
				stopAllActions();
				m_bIsRoll = false;

				if (marioStatus == MarioSt_LDown || marioStatus == MarioSt_RDown)
				{
					//回弹马里奥
					b2Vec2 marioVelocity = pMario->getBody()->GetLinearVelocity();
					pMario->getBody()->SetLinearVelocity(b2Vec2(marioVelocity.x, -marioVelocity.y));
				}
			}
			else
			{
				//马里奥地上状态,杀死马里奥
				GameScene::getInstance()->reduceLife();
			}
		}
		else
		{
			if ((pMario->getMarioStatus() & 0x1000) == 0)
			{
				//左向滚动
				m_bLeft = true;
				getBody()->SetLinearVelocity(b2Vec2(-MMSpeed_TortoiseDefense, oldVelocity.y));
			}
			else
			{
				//右向滚动
				m_bLeft = false;
				getBody()->SetLinearVelocity(b2Vec2(MMSpeed_TortoiseDefense, oldVelocity.y));
			}
			m_bIsRoll = true;
			stopAllActions();
			Animation * animation = AnimationCache::getInstance()->getAnimation("tortoiseDefend");
			runAction(Animate::create(animation));

			if (marioStatus == MarioSt_LDown || marioStatus == MarioSt_RDown)
			{
				//回弹马里奥
				b2Vec2 marioVelocity = pMario->getBody()->GetLinearVelocity();
				pMario->getBody()->SetLinearVelocity(b2Vec2(marioVelocity.x, -marioVelocity.y));
			}
		}
	}
	else
	{
		if (pMario->getMarioStatus() == MarioSt_LDown || pMario->getMarioStatus() == MarioSt_RDown ||
			pMario->getMarioStatus() == MarioSt_LTumble || pMario->getMarioStatus() == MarioSt_RTumble)
		{
			const Size & monsterSize = getMonsterSize();
			const Size & marioSize = pMario->getMarioSize();
			Vec2 pos = getPosition();
			Vec2 posM = pMario->getPosition();
			bool bMarioTumble = (pMario->getMarioStatus() == MarioSt_LTumble || pMario->getMarioStatus() == MarioSt_RTumble);

			if ((pos.y <= posM.y) &&
				(pos.x - posM.x > -monsterSize.width / 2 - marioSize.width / 2) &&
				(pos.x - posM.x < monsterSize.width / 2 + marioSize.width / 2))
			{
				//乌龟变为防守状态
				if (!bMarioTumble)
				{
					stopAllActions();
					getBody()->SetLinearVelocity(b2Vec2(0.0f, 0.0f));
					m_bIsDefend = true;
					m_bIsRoll = false;

					SpriteFrame * frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(
						"monster/tortoise_defend/tortoise_defend1.png");
					setSpriteFrame(frame);
					updateFixStatus = UpdateTortoise_Defend;
					playEffect(Effect_KillMonster);

					//回弹马里奥
					b2Vec2 marioVelocity = pMario->getBody()->GetLinearVelocity();
					pMario->getBody()->SetLinearVelocity(b2Vec2(marioVelocity.x, -marioVelocity.y));
				}
				else
				{
					if (posM.x >= pos.x)
					{
						//左向滚动
						m_bLeft = true;
						getBody()->SetLinearVelocity(b2Vec2(-MMSpeed_TortoiseDefense, 0.0f));
					}
					else
					{
						//右向滚动
						m_bLeft = false;
						getBody()->SetLinearVelocity(b2Vec2(MMSpeed_TortoiseDefense, 0.0f));
					}
					m_bIsDefend = true;
					m_bIsRoll = true;
					m_lastPos.set(getPosition());
					updateFixStatus = UpdateTortoise_Defend;
					stopAllActions();
					Animation * animation = AnimationCache::getInstance()->getAnimation("tortoiseDefend");
					runAction(Animate::create(animation));
				}
			}
			else
			{
				GameScene::getInstance()->reduceLife();
			}
		}
		else
		{
			GameScene::getInstance()->reduceLife();
		}
	}

}
Пример #20
0
void ofxGameCamera::update(ofEventArgs& args){	
	rotationChanged = false;
	positionChanged = false;
	if(applyTranslation){
		int multiplier = invertControls ? -1 : 1;
		if(ofGetKeyPressed('w') || (useArrowKeys && ofGetKeyPressed(OF_KEY_UP)) ){
			if(dampen){
				targetNode.dolly(-speed);
			}else{
				dolly(-speed);
			}
			positionChanged = true;
		}
		
		if(ofGetKeyPressed('s') || (useArrowKeys && ofGetKeyPressed(OF_KEY_DOWN)) ){
			if(dampen){
				targetNode.dolly(speed);
			}else{
				dolly(speed);
			}
			positionChanged = true;
		}
		
		if(ofGetKeyPressed('a') || (useArrowKeys && ofGetKeyPressed(OF_KEY_LEFT)) ){
			if(dampen){
				targetNode.truck(-speed);
			}else{
				truck(-speed);
			}
			positionChanged = true;
		}
		
		if(ofGetKeyPressed('d') || (useArrowKeys && ofGetKeyPressed(OF_KEY_RIGHT)) ){
			if(dampen){
				targetNode.truck(speed);
			}
			else{
				truck(speed);
			}
			positionChanged = true;
		}
		
		if(ofGetKeyPressed('c') || (useArrowKeys && ofGetKeyPressed(OF_KEY_PAGE_DOWN)) ){
			if(dampen){
				targetNode.boom(-speed*multiplier);
			}
			else{
				boom(-speed*multiplier);
			}
			positionChanged = true;
		}
		
		if(ofGetKeyPressed('e') || (useArrowKeys && ofGetKeyPressed(OF_KEY_PAGE_UP)) ){
			if(dampen){
				targetNode.boom(speed*multiplier);
			}
			else{
				boom(speed*multiplier);
			}
			positionChanged = true;
		}
	}
	
	if(applyRotation){
		if(ofGetKeyPressed('r')){
			targetZRot += rollSpeed;
			rotationChanged = true;
		}
		if(ofGetKeyPressed('q')){
			targetZRot -= rollSpeed;
			rotationChanged = true;
		}
	}
	
	if(dampen){
		setPosition(getPosition() + (targetNode.getPosition() - getPosition()) *.2);
	}
	ofVec2f mouse( ofGetMouseX(), ofGetMouseY() );
	if(usemouse && applyRotation && ofGetMousePressed(0)){
        if(!justResetAngles){

			float dx = (mouse.x - lastMouse.x) * sensitivityX;
			float dy = (mouse.y - lastMouse.y) * sensitivityY;
//			cout << "b4 DX DY! " << dx << " " << dy << " " << targetXRot << " " << targetYRot << endl;
			targetXRot += dx * (invertControls ? -1 : 1);
			targetYRot += dy * (invertControls ? -1 : 1);
//			targetYRot = ClampAngle(targetYRot, minimumY, maximumY);
//			targetXRot = ClampAngle(targetXRot, minimumX, maximumX);
//			cout << "after DX DY! " << dx << " " << dy << " " << targetXRot << " " << targetYRot << endl;
			rotationChanged = true;
		}
		justResetAngles = false;
	}
	
	if(rotationChanged){
		updateRotation();		
	}
	
	lastMouse = mouse;
    
	if(!ofGetMousePressed(0) && autosavePosition && (rotationChanged || positionChanged)){
		saveCameraPosition();
	}
}
Пример #21
0
 const Ogre::Vector3 getPlayerAbsolutePosition() const {return mPlayerRelativePosition + getPosition() + mPlayerDirection * getSize();}
Пример #22
0
void Circle3DOverlay::render(RenderArgs* args) {
    if (!_visible) {
        return; // do nothing if we're not visible
    }

    float alpha = getAlpha();

    if (alpha == 0.0) {
        return; // do nothing if our alpha is 0, we're not visible
    }
    
    const float FULL_CIRCLE = 360.0f;
    const float SLICES = 180.0f;  // The amount of segment to create the circle
    const float SLICE_ANGLE = FULL_CIRCLE / SLICES;

    //const int slices = 15;
    xColor color = getColor();
    const float MAX_COLOR = 255.0f;
    glColor4f(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha);


    glDisable(GL_LIGHTING);
    
    glm::vec3 position = getPosition();
    glm::vec3 center = getCenter();
    glm::vec2 dimensions = getDimensions();
    glm::quat rotation = getRotation();

    float glowLevel = getGlowLevel();
    Glower* glower = NULL;
    if (glowLevel > 0.0f) {
        glower = new Glower(glowLevel);
    }

    glPushMatrix();
        glTranslatef(position.x, position.y, position.z);
        glm::vec3 axis = glm::axis(rotation);
        glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z);
        glPushMatrix();
            glm::vec3 positionToCenter = center - position;
            glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z);
            glScalef(dimensions.x, dimensions.y, 1.0f);

            // Create the circle in the coordinates origin
            float outerRadius = getOuterRadius(); 
            float innerRadius = getInnerRadius(); // only used in solid case
            float startAt = getStartAt();
            float endAt = getEndAt();

            glLineWidth(_lineWidth);
            
            // for our overlay, is solid means we draw a ring between the inner and outer radius of the circle, otherwise
            // we just draw a line...
            if (getIsSolid()) {
                glBegin(GL_QUAD_STRIP);

                float angle = startAt;
                float angleInRadians = glm::radians(angle);
                glm::vec2 firstInnerPoint(cos(angleInRadians) * innerRadius, sin(angleInRadians) * innerRadius);
                glm::vec2 firstOuterPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);

                glVertex2f(firstInnerPoint.x, firstInnerPoint.y);
                glVertex2f(firstOuterPoint.x, firstOuterPoint.y);

                while (angle < endAt) {
                    angleInRadians = glm::radians(angle);
                    glm::vec2 thisInnerPoint(cos(angleInRadians) * innerRadius, sin(angleInRadians) * innerRadius);
                    glm::vec2 thisOuterPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);

                    glVertex2f(thisOuterPoint.x, thisOuterPoint.y);
                    glVertex2f(thisInnerPoint.x, thisInnerPoint.y);
                
                    angle += SLICE_ANGLE;
                }
            
                // get the last slice portion....
                angle = endAt;
                angleInRadians = glm::radians(angle);
                glm::vec2 lastInnerPoint(cos(angleInRadians) * innerRadius, sin(angleInRadians) * innerRadius);
                glm::vec2 lastOuterPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
            
                glVertex2f(lastOuterPoint.x, lastOuterPoint.y);
                glVertex2f(lastInnerPoint.x, lastInnerPoint.y);

                glEnd();
            } else {
                if (getIsDashedLine()) {
                    glBegin(GL_LINES);
                } else {
                    glBegin(GL_LINE_STRIP);
                }
                

                float angle = startAt;
                float angleInRadians = glm::radians(angle);
                glm::vec2 firstPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
                glVertex2f(firstPoint.x, firstPoint.y);

                while (angle < endAt) {
                    angle += SLICE_ANGLE;
                    angleInRadians = glm::radians(angle);
                    glm::vec2 thisPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
                    glVertex2f(thisPoint.x, thisPoint.y);

                    if (getIsDashedLine()) {
                        angle += SLICE_ANGLE / 2.0f; // short gap
                        angleInRadians = glm::radians(angle);
                        glm::vec2 dashStartPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
                        glVertex2f(dashStartPoint.x, dashStartPoint.y);
                    }
                }
            
                // get the last slice portion....
                angle = endAt;
                angleInRadians = glm::radians(angle);
                glm::vec2 lastOuterPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
                glVertex2f(lastOuterPoint.x, lastOuterPoint.y);
                glEnd();
            }
            
            // draw our tick marks
            // for our overlay, is solid means we draw a ring between the inner and outer radius of the circle, otherwise
            // we just draw a line...
            if (getHasTickMarks()) {
                glBegin(GL_LINES);

                // draw our major tick marks
                if (getMajorTickMarksAngle() > 0.0f && getMajorTickMarksLength() != 0.0f) {
                
                    xColor color = getMajorTickMarksColor();
                    glColor4f(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha);
                
                    float tickMarkAngle = getMajorTickMarksAngle();
                    float angle = startAt - fmod(startAt, tickMarkAngle) + tickMarkAngle; 
                    float angleInRadians = glm::radians(angle);
                    float tickMarkLength = getMajorTickMarksLength();
                    float startRadius = (tickMarkLength > 0.0f) ? innerRadius : outerRadius;
                    float endRadius = startRadius + tickMarkLength;

                    while (angle <= endAt) {
                        angleInRadians = glm::radians(angle);

                        glm::vec2 thisPointA(cos(angleInRadians) * startRadius, sin(angleInRadians) * startRadius);
                        glm::vec2 thisPointB(cos(angleInRadians) * endRadius, sin(angleInRadians) * endRadius);

                        glVertex2f(thisPointA.x, thisPointA.y);
                        glVertex2f(thisPointB.x, thisPointB.y);
                
                        angle += tickMarkAngle;
                    }
                }

                // draw our minor tick marks
                if (getMinorTickMarksAngle() > 0.0f && getMinorTickMarksLength() != 0.0f) {
                
                    xColor color = getMinorTickMarksColor();
                    glColor4f(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha);
                
                    float tickMarkAngle = getMinorTickMarksAngle();
                    float angle = startAt - fmod(startAt, tickMarkAngle) + tickMarkAngle; 
                    float angleInRadians = glm::radians(angle);
                    float tickMarkLength = getMinorTickMarksLength();
                    float startRadius = (tickMarkLength > 0.0f) ? innerRadius : outerRadius;
                    float endRadius = startRadius + tickMarkLength;

                    while (angle <= endAt) {
                        angleInRadians = glm::radians(angle);

                        glm::vec2 thisPointA(cos(angleInRadians) * startRadius, sin(angleInRadians) * startRadius);
                        glm::vec2 thisPointB(cos(angleInRadians) * endRadius, sin(angleInRadians) * endRadius);

                        glVertex2f(thisPointA.x, thisPointA.y);
                        glVertex2f(thisPointB.x, thisPointB.y);
                
                        angle += tickMarkAngle;
                    }
                }

                glEnd();
            }
            
 
        glPopMatrix();
    glPopMatrix();
    
    if (glower) {
        delete glower;
    }
}
Пример #23
0
//All Vectors are updated in here
void EnemyShip::tic(uint64_t time)
{
    if (isAlive())
    {
        if ((m_playerRef->getPosition() - m_position).Length() > LODDISTANCE)
        {
            if (flashtimer != 0)
            {
                m_LODmesh->setVisible(false);
                m_mesh->setVisible(false);
                flashtimer--;
            }
            else
            {
                m_mesh->setVisible(false);
                m_LODmesh->setVisible(true);
            }
        }
        else
        {
            if (flashtimer != 0)
            {
                m_LODmesh->setVisible(false);
                m_mesh->setVisible(false);
                flashtimer--;
            }
            else
            {
                m_mesh->setVisible(true);
                m_LODmesh->setVisible(false);
            }
        }
    }

    if (time == 0)
    {
        mat4 modelMtx = mat4::Scale(mODEL_SCALE) * mat4::Rotate(ROTATE_CONSTANT, vec3(0,1,0)) *
                        mat4::Rotate(ROTATE_CONSTANT, vec3(0,0,1));
        modelMtx *= mat4::Magic(getAimForward(), getAimUp(), getPosition());
        m_mesh->setModelMtx(modelMtx);
        m_LODmesh->setModelMtx(modelMtx);
        m_LODmesh->setVisible(true);
    }

    //printf("WT");

    dpos = (m_playerRef->getPosition() - m_position);
    if (isAlive() && dpos.Length() < MAXDISTANCE) {
        /** the normalized vector between the player and the enemy **/
        dpos = dpos.Normalized();

        // moving based on the player's direction and it's aiming direction
        m_position += m_playerRef->getMForward() * PATHVELOCITY * time + getAimForward() * AIMVELOCITY * time;

        /** 'scared ship' AI **/
        float aimAngle;
        float distance;
        /** the angle between the player's aim and the enemy's location:
         *  If the player is aiming near the enemy, it dodges **/
        aimAngle = 180 - 180.0f / 3.14159265f * acos(dpos.Dot(m_playerRef->getAimForward()));
        distance = (float)((m_playerRef->getPosition() - m_position).Length());
        if (aimAngle < MAXSCAREDANGLE)
        {
            /** If this is the first tic he needs to dodge, compute the dodge direction **/
            if (!dodging)
            {
                if (180.0f / 3.14159265f * acos(dpos.Dot(m_playerRef->getSide())) < 90)
                    dodgedir = 1;
                else
                    dodgedir = -1;
            }
            /** if he's dodged long enough, but is still being aimed at,
             *  dodge in the opposite direction **/
            if (dodgecounter == 0)
            {
                dodgecounter = DODGETIME;
                dodgedir = -dodgedir;
            }
            /** which direction to dodge in? **/
            vec3 motionDir = getScaredSide() / (aimAngle / MAXSCAREDANGLE) * MAXSCAREDSPEED * dodgedir *
                             ((DISTANCESCALE / distance) * (DISTANCESCALE / distance));
            /** move and dodge **/
            m_position += motionDir * time;
            dodging = true;
            /** count down - you can't dodge in the same direction forever **/
            dodgecounter--;
        }
        else
        {
            /** no longer being aimed at, dodging unnecessary **/
            dodging = false;
            dodgedir = 0;
            dodgecounter = DODGETIME;
        }

        /** setting the modelmatrix based on a constant scale and rotation,
         *  and the forward, up and position (aka Magic) - note that
         *  the enemy constantly aims at the player **/
        mat4 modelMtx = mat4::Scale(mODEL_SCALE) * mat4::Rotate(ROTATE_CONSTANT, vec3(0,1,0)) *
                        mat4::Rotate(ROTATE_CONSTANT, vec3(0,0,1));
        modelMtx *= mat4::Magic(getAimForward(), getAimUp(), getPosition());
        m_mesh->setModelMtx(modelMtx);
        m_LODmesh->setModelMtx(modelMtx);

        /** update the timer for shooting **/
        firingTimer += time;

        /** if it's time to shoot, let loose the cannons! (provided you're not behing the player) **/
        if (firingTimer > 600 /*&& 180.0f / 3.14159265f * acos(dpos.Dot(m_playerRef->getForward())) > 80*/)
        {
            firing = true;
            firingTimer = 0;
        }
        else
        {
            firing = false;
        }

        firing = firing && isAlive();
    }
    else if (isAlive())
    {
        m_up = m_playerRef->getAimUp();

        mat4 modelMtx = mat4::Scale(mODEL_SCALE) * mat4::Rotate(ROTATE_CONSTANT, vec3(0,1,0)) *
                        mat4::Rotate(ROTATE_CONSTANT, vec3(0,0,1));
        modelMtx *= mat4::Magic(getAimForward(), getAimUp(), getPosition());
        m_mesh->setModelMtx(modelMtx);
        m_LODmesh->setModelMtx(modelMtx);

        m_position = spawnpos;
    }
    else
    {
        explosionTic(time);
    }
}
Пример #24
0
std::vector<sf::RectangleShape> Robby::drawPen(int traceWidth, int r, int g, int b) {
    if (traceWidth != 0)
        penLines.push_back(drawLine(lastPoint,getPosition(),traceWidth,r,g,b));
    lastPoint = getPosition();
    return penLines;
}
Пример #25
0
void Player::update() {
    int thisMouseX = inputHandler->getMouseX();
    int thisMouseY = inputHandler->getMouseY();
    bool movement = false;
    this->isTouchingBelow = WorldHandler::getInstance()->belowWorldCollide(editPosition(), editScene());
    this->gravity();

    //velocity X calmers, world friction
    if(getVelocity().x > 0) {
        editVelocity().x -= 0.5;
    } else if(getVelocity().x < 0) {
        editVelocity().x += 0.5;
    }
    //get actual user input
    if((inputHandler->getSPACE() || inputHandler->getUP()) && isTouchingBelow && getVelocity().y == 0) {
        editVelocity().y += jumpHeight;
        movement = true;
    }
    if(inputHandler->getRIGHT()) {
        editVelocity().x += speed;
        movement = true;
    }
    if(inputHandler->getLEFT()) {
        editVelocity().x -= speed;
        movement = true;
    }

    //clamp the jump speed
    if(getVelocity().y < jumpHeight) {
        editVelocity().y = jumpHeight;
    }
    //clamp the running speed
    if(getVelocity().x > getMaxSpeedX()) {
        editVelocity().x = getMaxSpeedX();
    }
    if(getVelocity().x < -getMaxSpeedX()) {
        editVelocity().x = -getMaxSpeedX();
    }
    worldHandler->movementCheck(editPosition(), editVelocity(), editScene(), true, true);

    if(inputHandler->getQ() && inventoryItemDisplayAlpha < 0.9) {
        inv.backwards();
        inventoryItemDisplayAlpha = 1;
    }

    if(inputHandler->getE() && inventoryItemDisplayAlpha < 0.9) {
        inv.forwards();
        inventoryItemDisplayAlpha = 1;
    }

    //Item placement check
    if(inputHandler->getMOUSE1()) {
        if(inv.getSelectedPos() > inv.size() || inv.isEmpty()) {
            return;
        }
        //check if the item is even placeable
        if(inv.getSelected()->type->placeable) {
            //get a pointer to the item you're placing
            Item* item = inv.getSelected()->type;
            //get the distance between your character and your mouse
            float distance = Math::vectorDistance(getPosition().x+SPRITE_SIZE/2, getPosition().y+SPRITE_SIZE/2, thisMouseX, thisMouseY);
            if(distance < SPRITE_SIZE*3) {
                //get an instance of the tile you're hovering over
                Tile tile = *worldHandler->getTile(thisMouseX, thisMouseY);
                //make sure the tile is empty
                if(tile.id == T_sky) {
                    //swap the air tile for the tileID that is dropped
                    worldHandler->getTile(thisMouseX, thisMouseY) = &worldHandler->getTiles()[item->tileID];
                    //reduce the amount held
                    //this method also handles deletion
                    if(inv.reduceSelected()) {
                        inventoryItemDisplayAlpha = 1;
                    }
                }
            }
        }
    }

    //you can't mine whilst moving
    if(!movement) {
        //if the LMB is pressed and you're not already mining, start the checks to start mining
        if(inputHandler->getMOUSE0() && !mining) {
            //get the distance between the mouse and the player
            float distance = Math::vectorDistance(getPosition().x+SPRITE_SIZE/2, getPosition().y+SPRITE_SIZE/2, thisMouseX, thisMouseY);

            //only if the distance is less than the spritesize*3 then we should start mining
            if(distance < SPRITE_SIZE*3) {
                Tile tile = *worldHandler->getTile(thisMouseX, thisMouseY);
                if(tile.solid) {
                    miningTime = tile.strength;
                    selectedX = thisMouseX-(thisMouseX%SPRITE_SIZE);
                    selectedY = thisMouseY-(thisMouseY%SPRITE_SIZE);
                    mining = true;
                    timer.start();
                }
            }
        }
        //if you're currently mining then check you're still holding that LMB
        if(mining) {
            int x = thisMouseX-(thisMouseX%SPRITE_SIZE);
            int y = thisMouseY-(thisMouseY%SPRITE_SIZE);
            //check if you're still on the original tile
            if(x != selectedX || y!= selectedY) {
                this->stopMining();
            } else if(!inputHandler->getMOUSE0()) {
                this->stopMining();
            } else {
                //if the mining is still happening
                if(timer.elapsedTime() >= miningTime) {
                    inv.pickup(worldHandler->getItems()[worldHandler->getTile(thisMouseX, thisMouseY)->itemDrop], 1);
                    worldHandler->getTile(thisMouseX, thisMouseY) = &worldHandler->getTiles()[0];
                    this->stopMining();
                }
                else if(timer.elapsedTime() >= miningTime-(miningTime/4)) {
                    miningLevel = 3;
                } else if(timer.elapsedTime() >= miningTime/2) {
                    miningLevel = 2;
                } else if(timer.elapsedTime() >= miningTime/4) {
                    miningLevel = 1;
                }
            }
        }
    } else if(mining) {
        this->stopMining();
    }
}
Пример #26
0
void MobilEntity::move(sf::Vector2f deplacement)
{
	setPosition(sf::Vector2f(getPosition()->x + deplacement.x, getPosition()->y + deplacement.y));
}
Пример #27
0
void Platform::draw()
{
	//Object::draw();

	GraphicsManager &graphics_manager = GraphicsManager::getInstance();

	
	if (isItThick == false)
	{
		if (height <= 2)
		{

			for (int i = 0; i < size; i++)
			{
				Position temp(getPosition().getX() + i, getPosition().getY());

				graphics_manager.drawCh(temp, PLATFORM_THIN, thecolor);
			}


		}
		else
		{
			for (int j = 0; j < height; j++)
			{
				if (j == 0 || j == (height - 1))
				{
					for (int i = 0; i < size; i++)
					{

						Position temp(getPosition().getX() + i, getPosition().getY());

						graphics_manager.drawCh(temp, PLATFORM_THIN, thecolor);
						//graphics_manager.drawCh(temp, PLATFORM_THIN_WALL);
					}

				}
				else
				{
					Position temp(getPosition().getX(), getPosition().getY() + j);

					graphics_manager.drawCh(temp, PLATFORM_THIN_WALL, thecolor);
					temp.setXY(getPosition().getX() + size - 1, getPosition().getY() + j);
					graphics_manager.drawCh(temp, PLATFORM_THIN_WALL, thecolor);

				}



			} // end j for

			for (int i = 0; i < size; i++)
			{
				if (i <= size - 3)
				{
					Position temp(getPosition().getX() + i + 1, getPosition().getY() + height - 2);
					graphics_manager.drawCh(temp, PLATFORM_THIN, thecolor);
				}
				else
				{
					Position temp(getPosition().getX() + i, getPosition().getY() + height - 2);
					//graphics_manager.drawCh(temp, PLATFORM_THIN);
				}


				//graphics_manager.drawCh(temp, PLATFORM_THIN);
				//graphics_manager.drawCh(temp, PLATFORM_THIN_WALL);
			}
		} // end else

	}
	else
	{

		if (height <= 2)
		{

			for (int i = 0; i < size; i++)
			{
				Position temp(getPosition().getX() + i, getPosition().getY());

				graphics_manager.drawCh(temp, PLATFORM_THICK, thecolor);
			}


		}
		else
		{
			for (int j = 0; j < height; j++)
			{
				if (j == 0 || j == (height - 1))
				{
					for (int i = 0; i < size; i++)
					{
						Position temp(getPosition().getX() + i, getPosition().getY());

						graphics_manager.drawCh(temp, PLATFORM_THICK, thecolor);
						//graphics_manager.drawCh(temp, PLATFORM_THIN_WALL);
					}

				}
				else
				{
					Position temp(getPosition().getX(), getPosition().getY() + j);

					graphics_manager.drawCh(temp, PLATFORM_THICK_WALL, thecolor);
					temp.setXY(getPosition().getX() + size - 1, getPosition().getY() + j);
					graphics_manager.drawCh(temp, PLATFORM_THICK_WALL, thecolor);

				}



			} // end j for

			for (int i = 0; i < size; i++)
			{
				if (i <= size - 3)
				{
					Position temp(getPosition().getX() + i + 1, getPosition().getY() + height - 2);
					graphics_manager.drawCh(temp, PLATFORM_THICK, thecolor);
				}
				else
				{
					Position temp(getPosition().getX() + i, getPosition().getY() + height - 2);
					//graphics_manager.drawCh(temp, PLATFORM_THIN);
				}


				//graphics_manager.drawCh(temp, PLATFORM_THIN);
				//graphics_manager.drawCh(temp, PLATFORM_THIN_WALL);
			}
		} // end else


	}

	//  	GraphicsManager &graphics_manager = GraphicsManager::getInstance();
	// 	Box box = getBox();
	// 	std::stringstream curPos;
	// 	curPos << "Saus Position: " << getPosition().getX() << " , " << getPosition().getY() << " ";
	// 	curPos << "Height: " << box.getVertical() << " , " << "Width: " << box.getHorizontal();
	// 	graphics_manager.drawString(Position(0, 23), curPos.str(), LEFT_JUSTIFIED);
	// 	ResourceManager& resMgr = ResourceManager::getInstance();
	// 	Sprite* a = resMgr.getSprite("platform");
	// 	Frame b = a->getFrame(0);
	// 	graphics_manager.drawFrame(this->getPosition(), b, true, false, a->getColor());
	//graphics_manager.drawCh(getPosition(), SAUCER_CHAR, COLOR_GREEN); 
}
Пример #28
0
void GameMain::createMenu()
{
    Director::getInstance()->pause();
    
    auto winSize=Director::getInstance()->getWinSize();
    auto layer=Layer::create();

    //プラットフォームがウィンドウズ系の場合は終了ボタンを設置しない
#if !(CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
    auto sprite=Sprite::create("menuBoard_end.png");
#else
    auto sprite=Sprite::create("menuBoard.png");
#endif
    sprite->setPosition(winSize/2);
    layer->addChild(sprite);
    
    auto highScore=UserDefault::getInstance()->getIntegerForKey(HIGHSCORE_KEY,0);
    auto label=Label::createWithSystemFont(StringUtils::format("%d",highScore),"Marker Felt",48);
    label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT);
    label->setPosition(Vec2(650,1100));
    layer->addChild(label);
    
    auto button=MenuItemImage::create("menu_open.png","menu_open.png",[layer](Ref* pButton){
        layer->removeFromParent();
        Director::getInstance()->resume();
    });
    button->setAnchorPoint(Vec2::ANCHOR_TOP_RIGHT);
    button->setPosition(Vec2(winSize.width-1,winSize.height-1));
    
    //やり直し カードを初期配置に戻す
    auto resetButton=MenuItemImage::create("button_off.png"
                                           ,"button_on.png"
                                           ,[this](Ref* pButton){
                                               this->resetGame();
                                           });
    resetButton->setPosition(Vec2(290,700));
    
    //再配布 カードを配りなおす
    auto restartButton=MenuItemImage::create("button_off.png"
                                             ,"button_on.png"
                                             ,[this](Ref* pButton){
                                                 this->createCards();
                                                 this->resetGame();
                                             });
    restartButton->setPosition(Vec2(290,570));
    
    //helpボタン
    auto helpButton=MenuItemImage::create("button_help_off.png"
                                          ,"button_help_on.png"
                                          ,[this](Ref* pButton){
                                              this->createHelp();
                                          });
    helpButton->setPosition(Vec2(320,1200));
    
#if !(CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
    //アプリ終了ボタン
    auto apEndButton=MenuItemImage::create("button_off.png",
                                           "button_on.png"
                                           ,[this](Ref* pButton){
                                               this->unscheduleUpdate();
                                               this->unschedule(DRAG_SCHEDULE);
                                               Director::getInstance()->getActionManager()->pauseAllRunningActions();
                                               Director::getInstance()->getActionManager()->removeAllActions();
                                               
                                               Director::getInstance()->end();
                                               if(CC_TARGET_PLATFORM==CC_PLATFORM_IOS){
                                                   exit(0);
                                               }
                                           });
    apEndButton->setPosition(Vec2(350,320));
    
    auto menu=Menu::create(button,resetButton,restartButton,helpButton,apEndButton,NULL);
#else
    auto menu=Menu::create(button,resetButton,restartButton,helpButton,NULL);
#endif
    menu->setPosition(Vec2::ZERO);
    layer->addChild(menu);
    
    //山札からカードを引く枚数
    auto oneButtonOff=Sprite::create("button_off.png");
    oneButtonOff->setPosition(Vec2(290,850));
    layer->addChild(oneButtonOff);
    auto oneButton=Sprite::create("button_on.png");
    oneButton->setPosition(oneButtonOff->getPosition());
    layer->addChild(oneButton);
    
    auto threeButtonOff=Sprite::create("button_off.png");
    threeButtonOff->setPosition(Vec2(460,850));
    layer->addChild(threeButtonOff);
    auto threeButton=Sprite::create("button_on.png");
    threeButton->setPosition(threeButtonOff->getPosition());
    layer->addChild(threeButton);
    
    if(_talonLayer->getPullCount()==1){//カードが1枚の場合onebuttonを点灯
        threeButton->setVisible(false);
    }else{
        oneButton->setVisible(false);
    }
    
    auto listener=EventListenerTouchOneByOne::create();
    listener->onTouchBegan=[](Touch* touch,Event* event){return true;};
    listener->onTouchEnded=[this,oneButton,threeButton](Touch* touch,Event* event){
        auto position=touch->getLocation();
        
        if(oneButton->getBoundingBox().containsPoint(position)){//onebuttonがタッチされた
            if(!oneButton->isVisible()){//onebuttonが点灯状態ではない
                UserDefault::getInstance()->setIntegerForKey(PULLCOUNT_KEY,1);
                oneButton->setVisible(true);
                threeButton->setVisible(false);
                this->resetGame();
            }
        }else if(threeButton->getBoundingBox().containsPoint(position)){
            if(!threeButton->isVisible()){
                UserDefault::getInstance()->setIntegerForKey(PULLCOUNT_KEY,3);
                oneButton->setVisible(false);
                threeButton->setVisible(true);
                this->resetGame();
            }
        }
    };
    listener->setSwallowTouches(true);
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,layer);
    
    
    this->addChild(layer,convertLayerZPositionIntoInt(LayerZPosition::MENU));
}
Пример #29
0
//  ---------------------------------------------------------------- update()
//  updates car's position, velocity and rotation
void Car::update(float delta){
    logger.debug("Car::update()");
    
    // if right is clicked
    if(_move_right){
        // if is moving forward, then rotate (+)
        if(_move_up || getSpeed()->getX() > 0)
            // to drift when starts to speed up
            if(getSpeed()->getX() < gm.SPEED_INCREMENT * 4)
                setRotation(getRotation() - gm.ANGLE_INCREMENT / 2);
            else
				setRotation(getRotation() - gm.ANGLE_INCREMENT);
        // if is moving backward, then rotate (-)
        else if(_move_down || getSpeed()->getX() < 0)
            setRotation(getRotation() + gm.ANGLE_INCREMENT);
    }

    // if left is clicked
    if(_move_left){
        // if is moving forward, then rotate (-)
        if(_move_up || getSpeed()->getX() > 0)
            // to drift when starts to speed up
            if(getSpeed()->getX() < gm.SPEED_INCREMENT * 4)
				setRotation(getRotation() + gm.ANGLE_INCREMENT / 2);
            else
				setRotation(getRotation() + gm.ANGLE_INCREMENT);
        // if is moving backward, then rotate (+)
        else if(_move_down || getSpeed()->getX() < 0)
			setRotation(getRotation() - gm.ANGLE_INCREMENT);
    }
    
    // if moving forward and not max velocity
    if(_move_up && getSpeed()->getX() < gm.MAX_VELOCITY){
        getSpeed()->setX(getSpeed()->getX() + gm.SPEED_INCREMENT);
    }
    
    // if moving backwards
    if(_move_down && getSpeed()->getX() > -gm.MAX_VELOCITY/2){
        getSpeed()->setX(getSpeed()->getX() - gm.SPEED_INCREMENT);
    }
           
    // if not moving forward or backwards then it's
    if(!_move_up && !_move_down){
        if(getSpeed()->getX() > 0)
            getSpeed()->setX(getSpeed()->getX() - gm.SPEED_INCREMENT/2);
        if(getSpeed()->getX() < 0)
            getSpeed()->setX(getSpeed()->getX() + gm.SPEED_INCREMENT/2);
    }

    double new_pos_x = getPosition()->getX() + getSpeed()->getX() * delta * (-sin(getRotation() * PI/180));
    double new_pos_y = getPosition()->getY() + getSpeed()->getX() * delta * ( cos(getRotation() * PI/180));
    double new_pos_z = 0.0f;
    
     //define car limits on map
    if(std::abs(new_pos_x) > gm.TRACK_LIMITS){
        new_pos_x = getPosition()->getX();
    }
    if(std::abs(new_pos_y) > gm.TRACK_LIMITS){
        new_pos_y = getPosition()->getY();
    }
    
    setPosition(new Vector3(new_pos_x, new_pos_y, new_pos_z));
};
Пример #30
0
bool Scene_Selector_4::init()
{

	index_now = 0;

	Layer::init();


	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("Scene_4/stages_theme6-hd.plist");

	auto bg = Sprite::createWithSpriteFrameName("ss_bg.png");
	bg->setPosition(960 / 2, 640 / 2);
	this->addChild(bg);


	auto bg1 = Sprite::createWithSpriteFrameName("ss_cloud.png");
	bg1->setPosition(960 / 2, 640 / 2);
	this->addChild(bg1);


	sprite_tower_able = Sprite::create();

	this->addChild(sprite_tower_able);
	sprite_tower_able->setPosition(960 / 2, 640 / 2 - 150);
	sprite_tower_able;;


	auto menu_play = MenuItemSprite::create(Sprite::createWithSpriteFrameName("ss_play_normal_CN.png"),
		Sprite::createWithSpriteFrameName("ss_play_pressed_CN.png"),
		[=](Ref*)
	{

		if (sprite_lock->isVisible() == true)return;

		Audio::play_Button();
		callback_play();
	}
	);
	menu_play->setPosition(960 / 2, 640 / 2 - 250);


	auto menu_back = MenuItemSprite::create(Sprite::createWithSpriteFrameName("ss_back_normal.png"),
		Sprite::createWithSpriteFrameName("ss_back_pressed.png"),
		[=](Ref*)
	{
		Audio::play_Button();
		SpriteFrameCache::getInstance()->removeSpriteFramesFromFile("Scene_4/stages_theme6-hd.plist");

		Director::getInstance()->popScene();
	}
	);
	menu_back->setPosition(960 / 2 - 420, 640 - 28);




	auto menu_help = MenuItemSprite::create(Sprite::createWithSpriteFrameName("ss_help_normal.png"),
		Sprite::createWithSpriteFrameName("ss_help_pressed.png"),
		[=](Ref*)
	{

		Audio::play_Button();
		Director::getInstance()->pushScene(Scene_Help::createScene());

	}
	);
	menu_help->setPosition(960 / 2 + 420, 640 - 28);








	menu_lef = MenuItemSprite::create(Sprite::createWithSpriteFrameName("recommend_left_normal.png"),
		Sprite::createWithSpriteFrameName("recommend_left_pressed.png"),
		[=](Ref*)
	{
		Audio::play_Button();
		if (index_now <= 0)return;
		setIndex(--index_now);

	}
	);
	menu_lef->setPosition(960 / 2 - 400, 640 / 2);




	menu_rig = MenuItemSprite::create(Sprite::createWithSpriteFrameName("recommend_right_normal.png"),
		Sprite::createWithSpriteFrameName("recommend_right_pressed.png"),
		[=](Ref*)
	{
		Audio::play_Button();
		if (index_now >= INDEX_MAX)return;
		setIndex(++index_now);


	}
	);
	menu_rig->setPosition(960 / 2 + 400, 640 / 2);


	menu_lef->setScale(2.0);
	menu_rig->setScale(2.0);



	sprite = Sprite::create();
	sprite->setPosition(960 / 2, 640 / 2 + 80);

	auto menu_play1 = MenuItemSprite::create(Sprite::createWithSpriteFrameName("ss_map01.png"),
		Sprite::createWithSpriteFrameName("ss_map01.png"),
		[=](Ref*)
	{
		if (sprite_lock->isVisible() == true)return;

		Audio::play_Button();

		callback_play();
	}
	);
	menu_play1->setPosition(sprite->getPosition());



	auto dic = Dictionary::createWithContentsOfFile("string_CN.plist");
	auto label1 = Label::create(((String*)dic->objectForKey("select"))->getCString(), FONT, 35);
	label1->setPosition(960 / 2, 640 - 30);
	this->addChild(label1);



	auto menu = Menu::create(menu_play, menu_back, menu_help, menu_lef, menu_rig, menu_play1, nullptr);
	this->addChild(menu);
	menu->setPosition(0, 0);

	this->addChild(sprite);


	sprite_allclear = Sprite::createWithSpriteFrameName("gainhonor_4.png");
	this->addChild(sprite_allclear);
	sprite_allclear->setPosition(960 / 2, 640 / 2);
	sprite_allclear;;




	sprite_lev = Sprite::createWithSpriteFrameName("gainhonor_3.png");
	this->addChild(sprite_lev);
	sprite_lev->setPosition(960 / 2 + 150, 640 / 2);
	sprite_lev;;

	sprite_lock = Sprite::createWithSpriteFrameName("ss_locked_icon.png");
	this->addChild(sprite_lock);
	sprite_lock->setPosition(960 / 2 + 150, 640 / 2);

	sprite_lock_1 = Sprite::createWithSpriteFrameName("ss_locked_CN.png");
	this->addChild(sprite_lock_1);
	sprite_lock_1->setPosition(menu_play->getPosition());


	setIndex(index_now);

	return true;
}