示例#1
0
void Labyrinth::goNorth() {
	if (hasNorth()) {
		m_precedent = m_current;
		m_current.y--;
		newPosition();
	}
}
示例#2
0
void Labyrinth::goEast() {
	if (hasEast()) {
		m_precedent = m_current;
		m_current.x++;
		newPosition();
	}
}
示例#3
0
/* Initialisation d'un L-System a partir d'une chaine de caracteres ou sont stockes les parametres */
Lsystem initLsystem(String strLsystem)
{
    Lsystem lsystem;
    lsystem.name = NULL;
    lsystem.variables = NULL;
    lsystem.constants = NULL;
    lsystem.start = NULL;
    lsystem.rules = NULL;
    lsystem.generations = NULL;
    lsystem.position = NULL;

    char delims[] = "\n";

    lsystem.name = strtok( strLsystem, delims );
    lsystem.angle = atoi(strtok( NULL, delims ));
    lsystem.variables = strtok( NULL, delims );
    lsystem.constants = strtok( NULL, delims );
    lsystem.start = strtok( NULL, delims );
    String result = NULL;
    result = strtok( NULL, delims );
    while( result != NULL ) {
        lsystem.rules=addRule(lsystem.rules,result);
        result = strtok( NULL, delims );
    }
    lsystem.generations = (Generations*)malloc(sizeof(Generations));
    lsystem.generations = newGeneration(lsystem.generations,lsystem);
    lsystem.position = (Position*)malloc(sizeof(Position));
    lsystem.position = newPosition(lsystem.position);
    return lsystem;
}
示例#4
0
文件: game.c 项目: idr77/SnakeGame
/* Fonctions de jeu */
void initGame(Damier *map, Snake *snake)
{
	CaseSnake pos[MAXSNAKE];
	int i;
	
	pos[0] = newCaseSnake(QUEUE, newPosition(MAXCASES/2 , MAXCASES/2));
	pos[1] = newCaseSnake(CORPS, newPosition(MAXCASES/2 + 1, MAXCASES/2));
	pos[2] = newCaseSnake(TETE, newPosition(MAXCASES/2 + 2, MAXCASES/2));	
	
	for (i = 3; i < MAXSNAKE ; i++)
		pos[i] = newCaseSnake(VOID, newPosition(0,0));
		
	*snake = newSnake(2,0,pos);
	setPositionsToMap(map, snake);
	
}
示例#5
0
void Labyrinth::goWest() {
	if (hasWest()) {
		m_precedent = m_current;
		m_current.x--;
		newPosition();
	}
}
示例#6
0
DMG* HostileNPC::interact(Player *p, Field** map) {
        DMG* o = NULL;
        if(coolOff > 0) { // not ready to do anything
            coolOff--;
            return 0;
        }
        int x = position.x/50, y = position.y/50;
        for(int i = -1; i <= 1; i++) { //for each of neighbour fields
            for(int j = -1; j <= 1; j++) {
                if(map[x+i][y+j].state == Character) { //if there is a character nearby
                    // kill him!
                    int dmg = rand()%(p->getMaxHealth()/2);
                    p->setHealth(p->getHealth()-dmg);
                    coolOff = 60; // and rest
                    o = new DMG(dmg, false, p->getPosition());
                    return o;
                }
            }
        }
        // going somewhere
        if(!destinationSet) { //if there is no destination point for him
            for(int i = -1; i <= 1; i++) {
                for(int j = -1; j <= 1; j++) {
                    if(map[x+i][y+j].state == Empty && rand()%100 < 5) { //maybe it could be good
                        destination = sf::Vector2f((x+i)*50+20, (y+j)*50+20); //set it!
                        destinationSet = true;
                    }
                }
            }
        } else { //if we have somewhere to go
            int d_x = destination.x - position.x,
                d_y = destination.y - position.y; //calculate distance
            d_x = (d_x > 0) ? 2 : ((d_x < 0) ? -2 : 0); // set delta limits
            d_y = (d_y > 0) ? 2 : ((d_y < 0) ? -2 : 0);
            sf::Vector2f newPosition(position.x + d_x, position.y + d_y); // get new position
            if(map[int(newPosition.x/50)][int(newPosition.y/50)].state != Empty && //check if it's legal
                map[int(newPosition.x/50)][int(newPosition.y/50)].entity != this) {
                destination = sf::Vector2f(0, 0); //if not - reset vector
            destinationSet = false;
            coolOff = 120;
            } else { //if it's legal
                if(d_y > 0) motion.y = 1; //check motion animation frame
                if(d_y < 0) motion.y = -1;
                if(d_x > 0) motion.x = 1;
                if(d_x < 0) motion.x = -1;
                this->setPosition(newPosition); //set position on map
                map[x][y].state = Empty; //reset old field state
                map[x][y].entity = NULL; //and below set new one
                map[int(newPosition.x/50)][int(newPosition.y/50)].state = Enemy;
                map[int(newPosition.x/50)][int(newPosition.y/50)].entity = this;
                motion.x = motion.y = 0; //reset motion
            }
            if(d_x < 2 && d_x > -2 && d_y < 2 && d_y > -2) { //if we've reached our destination point
                destination = sf::Vector2f(0, 0); //reset vector
            destinationSet = false;
            coolOff = 120;
        }
    }
    return o;
}
示例#7
0
void Particle::update(float timeSinceLastUpdate)
{
    const Point &position = getPosition();
    const Vector3D &velocity = getVelocity();

    // decrease lifetime
    _lifetime -= timeSinceLastUpdate;

    // compute new position
    float speed = sqrt( velocity.x*velocity.x + velocity.y*velocity.y + velocity.z*velocity.z );
    if ( speed < 0.1 )
    {
        setVelocity( Vector3D( 0.0, 0.0, 0.0 ) );
    }
    Point newPosition( position.x + velocity.x * timeSinceLastUpdate,
                      position.y + velocity.y * timeSinceLastUpdate + 0.5 * GRAVITATIONAL_ACCELARATION * timeSinceLastUpdate * timeSinceLastUpdate,
                      position.z + velocity.z * timeSinceLastUpdate );
    Vector3D newVelocity( velocity.x, velocity.y + GRAVITATIONAL_ACCELARATION * timeSinceLastUpdate, velocity.z );

    // reflect and slow down the particle, if it hits the ground
    if( newPosition.y < _radius)
    {
        newVelocity = Vector3D(newVelocity.x * 0.4, -newVelocity.y * 0.4, newVelocity.z * 0.4);
        newPosition = Point(newPosition.x, 0.0 + _radius, newPosition.z);
    }

    // update configuration
    setPosition( newPosition );
    setVelocity( newVelocity );

}
示例#8
0
void Labyrinth::goSouth() {
	if (hasSouth()) {
		m_precedent = m_current;
		m_current.y++;
		newPosition();
	}
}
示例#9
0
Position* Position::translate(Position& offset)
{
	Position* p = newPosition();
	for (int i = 0; i < dimension(); i++)
		p->setAt(i, at(i) + offset.at(i));
	return p;
}
示例#10
0
void GamePanel::UpdateDrag(){
    	sf::Vector2f mousePosition(sf::Mouse::getPosition(*Drawn::gameWindow).x,sf::Mouse::getPosition(*Drawn::gameWindow).y);
	if(dragOffset.x == -1 && dragOffset.y == -1)
		dragOffset = mousePosition - GetPosition();
	//std::cout << "Offsets X: " << std::to_string(offset.x) << " Y: " << std::to_string(offset.y) << std::endl;
	sf::Vector2f newPosition(mousePosition.x - dragOffset.x - 8,mousePosition.y - dragOffset.y - 8);
	SetPosition(newPosition.x,newPosition.y);
};
示例#11
0
文件: game.c 项目: idr77/SnakeGame
bool playGame(Affichage A, Damier *map, Snake *snake, Sound sound)
{
	int end = 0;
	bool win = FALSE;
	Position newPos = initPosition();
	Input input = initInput();
	Chrono chrono = initChrono();
	Timer timer = initTimer();
	
	
	setProiesToMap(map);
	
	drawTile(A, TILE_TITLE);
	drawTextChrono(chrono, A);
	drawMap(A, *map, newPosition(MAXCASES/2 + 3,MAXCASES/2), *snake);

	startChrono(&chrono);
	while (1)
	{
		
		setTimer(&timer);
		newPos = updatePositions(map, snake, &input);
		
		if (input.end)
			break;

		if (testPosMap(newPos))
		{
			end = addPositionSnake(map, snake, newPos, sound);
			if (end)
			{
				win = FALSE;
				break;
			}
		}
		
		setPositionsToMap(map, snake);
		drawChrono(chrono, A);
		drawMap(A, *map, newPos, *snake);
		
		if(endChrono(chrono))
		{
			win = FALSE;
			break;
		}
		
		if (endGame(map))
		{
			win = TRUE;
			break;
		}
		
		reguleFPS(&timer);
	}
	
	deleteChrono(&chrono);
	return win;
}
示例#12
0
	void King::placeKing(cg::Vector3d position, float rot)
	{
		cg::Vector3d center = position;
		center[1] = center[1]+3.2;
		newPosition(center);
		_position = position;
		_rotation = (rot*180)/3.14;
		
	}
示例#13
0
MManipData componentScaleManip::manipToPlugConversion(unsigned index) {
	MObject obj = MObject::kNullObj;

	MFnScaleManip scaleManip(fScaleManip);
	if (index < (unsigned)numComponents)
	{
		//
		// Now we need to determine the scaled position of the CV specified by 
		// index.
		//

		MVector scaleVal;
		getConverterManipValue(scaleManip.scaleIndex(), scaleVal);

		// Determine the vector from the centroid to the CV
		//
		MVector positionVec = initialPositions[index] - centroid;

		// Scale the vector
		//
		MVector newPosition(positionVec.x*scaleVal.x, 
			positionVec.y*scaleVal.y, positionVec.z*scaleVal.z);

		// Form the vector from the initial position to the new position.
		//
		newPosition = newPosition - positionVec;

		// Move the control point from the initial control point position along
		// the vector.  Control point positions are always measured relative to
		// the initial position of the control point, which is why a separate 
		// array of control point positions is required.
		//
		newPosition += initialControlPoint[index];

		MFnNumericData numericData;
		obj = numericData.create( MFnNumericData::k3Double );
		numericData.setData(newPosition.x,newPosition.y,newPosition.z);

		return MManipData(obj);
	}

	// If we entered the handler with an invalid index, print an error and
	// return.  The callback should only be called for indices from 0 to
	// numComponents-1.
	//

	MGlobal::displayError("Invalid index in scale changed callback!");

	// For invalid indices, return vector of 0's
	MFnNumericData numericData;
	obj = numericData.create( MFnNumericData::k3Double );
	numericData.setData(0.0,0.0,0.0);

	return obj;
	
}
示例#14
0
//---------------------------------------------------------------------------
int32_t GameCamera::activate(void)
{
	//------------------------------------------
	// If camera is already active, just return
	if (ready && active)
		return (NO_ERROR);
	//---------------------------------------------------------
	// Camera always starts pointing at first mover in lists
	// CANNOT be infinite because we don't allow missions without at least 1
	// player mech!!
	MoverPtr firstMover = nullptr;
	if (ObjectManager->getNumMovers() > 0)
	{
		int32_t i  = 0;
		firstMover = ObjectManager->getMover(i);
		while (firstMover &&
			((firstMover->getCommander()->getId() != Commander::home->getId()) ||
				!firstMover->isOnGUI()))
		{
			i++;
			if (i == ObjectManager->getNumMovers())
				break;
			firstMover = ObjectManager->getMover(i);
		}
	}
	if (firstMover)
	{
		Stuff::Vector3D newPosition(firstMover->getPosition());
		setPosition(newPosition);
	}
	if (land)
	{
		land->update();
	}
	allNormal();
	// updateDaylight(true);
	lastShadowLightPitch = lightPitch;
	// Startup the SKYBox
	int32_t appearanceType					= (GENERIC_APPR_TYPE << 24);
	AppearanceTypePtr genericAppearanceType = nullptr;
	genericAppearanceType = appearanceTypeList->getAppearance(appearanceType, "skybox");
	if (!genericAppearanceType)
	{
		char msg[1024];
		sprintf(msg, "No Generic Appearance Named %s", "skybox");
		Fatal(0, msg);
	}
	theSky = new GenericAppearance;
	gosASSERT(theSky != nullptr);
	//--------------------------------------------------------------
	gosASSERT(genericAppearanceType->getAppearanceClass() == GENERIC_APPR_TYPE);
	theSky->init((GenericAppearanceType*)genericAppearanceType, nullptr);
	theSky->setSkyNumber(mission->theSkyNumber);
	return NO_ERROR;
}
TSegment
TSegment::RotateAround(
    const Coords::TColRowPoint& pivot,
    EMoveOperations direction
) const {
    static const auto shiftCoordsLeft
        = [](const Coords::THexPoint& p) -> Coords::THexPoint {
        //    x y z
        // -> y z x
        return Coords::THexPoint(p.Y, p.Z, p.X);
    };
    static const auto shiftCoordsRight
        = [](const Coords::THexPoint& p) -> Coords::THexPoint {
        //    x y z
        // -> z x y
        return Coords::THexPoint(p.Z, p.X, p.Y);
    };
    static const auto invertSigns
        = [](const Coords::THexPoint& p) -> Coords::THexPoint {
        return Coords::THexPoint(-1* p.X, -1 * p.Y, -1 * p.Z);
    };

    Coords::THexPoint hexPivot = Coords::ToHex(pivot);
    Coords::THexPoint hexSelf = Coords::ToHex(Position);

    Coords::THexPoint hexSelfLocal(
        hexSelf.X - hexPivot.X,
        hexSelf.Y - hexPivot.Y,
        hexSelf.Z - hexPivot.Z
    );

    Coords::THexPoint newHexSelfLocal = hexSelfLocal;
    switch (direction) {
        case EMoveOperations::ROTATE_CLOCKWISE: {
            newHexSelfLocal = invertSigns(shiftCoordsLeft(hexSelfLocal));
            break;
        }
        case EMoveOperations::ROTATE_ANTI_CLOCKWISE: {
            newHexSelfLocal = invertSigns(shiftCoordsRight(hexSelfLocal));
            break;
        }
        default: {
            throw TException("Invalid rotation operation recieved in ")
                << __FILE__ << ":" << __LINE__;
        }
    }

    Coords::THexPoint newPosition(
        hexPivot.X + newHexSelfLocal.X,
        hexPivot.Y + newHexSelfLocal.Y,
        hexPivot.Z + newHexSelfLocal.Z
    );

    return TSegment(Coords::FromHex(newPosition));
}
示例#16
0
void Spectrometer_Control::updateCurrentPosition(int steps, bool dir)
{
    //qDebug() << "Updating current position with " << QString::number(steps) << " in direction " << QString::number(dir);
    steps = fabs(steps);
    if(dir == true)
        MonoPos += steps;
    else
        MonoPos -= steps;
    emit positionChanged();
    emit newPosition(steps, dir);
    //qDebug() << "New Monopos: " << QString::number(MonoPos);
}
示例#17
0
void PageViewportControllerClientQt::setContentRectVisiblePositionAtScale(const QPointF& location, qreal itemScale)
{
    ASSERT(itemScale >= 0);

    scaleContent(itemScale);

    // To animate the position together with the scale we multiply the position with the current scale
    // and add it to the page position (displacement on the flickable contentItem because of additional items).
    QPointF newPosition(m_pageItem->position() + location * itemScale);

    m_viewportItem->setContentPos(newPosition);
}
示例#18
0
bool AddressManager::handleRelativeViewpoint(const QString& lookupString, bool shouldFace) {
    const QString FLOAT_REGEX_STRING = "([-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?)";
    const QString SPACED_COMMA_REGEX_STRING = "\\s*,\\s*";
    const QString POSITION_REGEX_STRING = QString("\\/") + FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING +
        FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING + FLOAT_REGEX_STRING + "\\s*(?:$|\\/)";
    const QString QUAT_REGEX_STRING = QString("\\/") + FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING +
        FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING + FLOAT_REGEX_STRING + SPACED_COMMA_REGEX_STRING +
        FLOAT_REGEX_STRING + "\\s*$";
    
    QRegExp positionRegex(POSITION_REGEX_STRING);
    
    if (positionRegex.indexIn(lookupString) != -1) {
        // we have at least a position, so emit our signal to say we need to change position
        glm::vec3 newPosition(positionRegex.cap(1).toFloat(),
                              positionRegex.cap(2).toFloat(),
                              positionRegex.cap(3).toFloat());
        
        if (!isNaN(newPosition.x) && !isNaN(newPosition.y) && !isNaN(newPosition.z)) {
            glm::quat newOrientation;
            
            QRegExp orientationRegex(QUAT_REGEX_STRING);
            
            // we may also have an orientation
            if (lookupString[positionRegex.matchedLength() - 1] == QChar('/')
                && orientationRegex.indexIn(lookupString, positionRegex.matchedLength() - 1) != -1) {
                
                glm::quat newOrientation = glm::normalize(glm::quat(orientationRegex.cap(4).toFloat(),
                                                                    orientationRegex.cap(1).toFloat(),
                                                                    orientationRegex.cap(2).toFloat(),
                                                                    orientationRegex.cap(3).toFloat()));
                
                if (!isNaN(newOrientation.x) && !isNaN(newOrientation.y) && !isNaN(newOrientation.z)
                    && !isNaN(newOrientation.w)) {
                    emit locationChangeRequired(newPosition, true, newOrientation, shouldFace);
                    return true;
                } else {
                    qDebug() << "Orientation parsed from lookup string is invalid. Will not use for location change.";
                }
            }
            
            emit locationChangeRequired(newPosition, false, newOrientation, shouldFace);
            
        } else {
            qDebug() << "Could not jump to position from lookup string because it has an invalid value.";
        }
        
        return true;
    }
    
    return false;
}
void QtViewportInteractionEngine::setItemRectVisible(const QRectF& itemRect)
{
    if (itemRect.isEmpty())
        return;

    qreal itemScale = m_viewport->width() / itemRect.width();

    m_content->setContentsScale(itemScale);

    // To animate the position together with the scale we multiply the position with the current scale
    // and add it to the page position (displacement on the flickable contentItem because of additional items).
    QPointF newPosition(m_content->pos() + (itemRect.topLeft() * itemScale));

    m_viewport->setContentPos(newPosition);
}
void DynamicsMotionState::setWorldTransform(const btTransform& transform)
{
//  DALI_LOG_INFO(Debug::Filter::gDynamics, Debug::Verbose, "%s\n", __PRETTY_FUNCTION__);

  // get updated parameters
  const btVector3& origin( transform.getOrigin() );
  const btQuaternion rotation( transform.getRotation() );
  const btVector3& axis( rotation.getAxis() );
  const btScalar& angle( rotation.getAngle() );

  Vector3 newPosition( origin.x(), origin.y(), origin.z() );
  const Vector3 newAxis( axis.x(), axis.y(), axis.z() );
  Quaternion newRotation( float(angle), newAxis );

  // set the nodes updated params
  mDynamicsBody.SetNodePositionAndRotation( newPosition, newRotation );
}
示例#21
0
void QtViewportHandler::setPageItemRectVisible(const QRectF& itemRect)
{
    ASSERT_WITH_MESSAGE(m_suspendCount,
        "setPageItemRectVisible has to be guarded using a ViewportUpdateDeferrer.");

    if (itemRect.isEmpty())
        return;

    qreal itemScale = m_viewportItem->width() / itemRect.width();

    m_pageItem->setContentsScale(itemScale);

    // To animate the position together with the scale we multiply the position with the current scale
    // and add it to the page position (displacement on the flickable contentItem because of additional items).
    QPointF newPosition(m_pageItem->pos() + (itemRect.topLeft() * itemScale));

    m_viewportItem->setContentPos(newPosition);
}
TEST_F(HTMLTextFormControlElementTest, SpellCheckDoesNotCauseUpdateLayout)
{
    HTMLInputElement* input = toHTMLInputElement(document().getElementById("input"));
    input->focus();
    input->setValue("Hello, input field");
    VisibleSelection oldSelection = document().frame()->selection().selection();

    Position newPosition(input->innerEditorElement()->firstChild(), 3);
    VisibleSelection newSelection(newPosition, TextAffinity::Downstream);
    document().frame()->selection().setSelection(newSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle | FrameSelection::DoNotUpdateAppearance);
    ASSERT_EQ(3, input->selectionStart());

    Persistent<SpellChecker> spellChecker(SpellChecker::create(page().frame()));
    forceLayoutFlag();
    int startCount = layoutCount();
    spellChecker->respondToChangedSelection(oldSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
    EXPECT_EQ(startCount, layoutCount());
}
示例#23
0
void MovingObject::updatePosition( int timeStep ) {
  if ( MINIMUM_VELOCITY > this->velocity ) {
    return;
  }

  if ( this->direction.isNull() ) {
    return;
  }

  this->lastDirection = this->direction;

  double timeFactor = timeStep / 1000.0f;

  QPointF newPosition( this->direction );
  newPosition *= this->velocity * timeFactor;
  newPosition += this->position;

  int oldXHalfBlock = this->position.x() / 0.5f;
  int oldYHalfBlock = this->position.y() / 0.5f;
  int newXHalfBlock = newPosition.x() / 0.5f;
  int newYHalfBlock = newPosition.y() / 0.5f;

  bool crossingX =
    oldXHalfBlock != newXHalfBlock &&
    ( MIN( oldXHalfBlock, newXHalfBlock ) % 2 ) == 0;
  bool crossingY =
    oldYHalfBlock != newYHalfBlock &&
    ( MIN( oldYHalfBlock, newYHalfBlock ) % 2 ) == 0;

  if ( crossingX || crossingY ) {
    if ( this->crossingBlockCenter( timeStep, newPosition ) ) {
      return;
    }
  }

  if ( ! this->testMovement( newPosition ) ) {
    // if you can't move, center at current block
    newPosition.setX( this->alignToCenter( this->position.x() ) );
    newPosition.setY( this->alignToCenter( this->position.y() ) );
    this->direction = QPoint();
  }

  this->position = newPosition;
}
示例#24
0
/*
* @method
*   bool Board::validMoveToPosition(Position pos, CARDINAL_DIRECTIONS direction)
*     - validates the move from Position pos to a given Cardinal Direction
*   Author: Mark Sands
*   Date modified: 1-25-11
*/
bool Board::validMoveToPosition(const Position& pos, CARDINAL_DIRECTIONS direction)
{
    Position newPosition(emptySlotIndex);
    newPosition.setBoardSize(size_);

    newPosition += pos;

    if ( !newPosition.valid() )
        return false;

    if (direction == NORTH || direction == WEST) {
        if ( tokenForPosition(newPosition) != RED )
            return false;
    } else {
        if ( tokenForPosition(newPosition) != BLUE )
            return false;
    }

    return true;
}
示例#25
0
void Character::moveTo(const Position &pos) {
    int moveTime = 1000/getRealSpeed();

    // Timer speed
    _speedTimer.mark();
    if(_speedTimer.timemsec()<moveTime) {
        return;
    } else {
        _speedTimer.start();

        // Move
        Position distance(pos.x()-this->getPosition().x(), pos.y()-this->getPosition().y());
        int dirX = distance.x()==0? 0 : distance.x()/abs(distance.x());
        int dirY = distance.y()==0? 0 : distance.y()/abs(distance.y());
        Position direction(dirX, dirY);

        Position newPosition(getPosition().x()+direction.x(), getPosition().y()+direction.y());
        this->setPosition(newPosition);
    }
}
示例#26
0
QGeoPositionInfoSource *GpsLocation::getGpsSource()
{
	if (haveSource == NOGPS)
		return 0;

	if (!m_GpsSource) {
		m_GpsSource = QGeoPositionInfoSource::createDefaultSource(this);
		if (m_GpsSource != 0) {
#if defined(Q_OS_IOS)
			// at least Qt 5.6.0 isn't doing things right on iOS - it MUST check for permission before
			// accessing the position source
			// I have a hacked version of Qt 5.6.0 that I will build the iOS binaries with for now;
			// this test below righ after creating the source checks if the location service is disabled
			// and set's an error right when the position source is created to indicate this
			if (m_GpsSource->error() == QGeoPositionInfoSource::AccessError) {
				haveSource = NOGPS;
				emit haveSourceChanged();
				m_GpsSource = NULL;
				return NULL;
			}
#endif
			haveSource = (m_GpsSource->supportedPositioningMethods() & QGeoPositionInfoSource::SatellitePositioningMethods) ? HAVEGPS : NOGPS;
			emit haveSourceChanged();
#ifndef SUBSURFACE_MOBILE
			if (verbose)
#endif
				status(QString("Created position source %1").arg(m_GpsSource->sourceName()));
			connect(m_GpsSource, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(newPosition(QGeoPositionInfo)));
			connect(m_GpsSource, SIGNAL(updateTimeout()), this, SLOT(updateTimeout()));
			connect(m_GpsSource, SIGNAL(error(QGeoPositionInfoSource::Error)), this, SLOT(positionSourceError(QGeoPositionInfoSource::Error)));
			setGpsTimeThreshold(prefs.time_threshold);
		} else {
#ifdef SUBSURFACE_MOBILE
			status("don't have GPS source");
#endif
			haveSource = NOGPS;
			emit haveSourceChanged();
		}
	}
	return m_GpsSource;
}
示例#27
0
文件: Hive.cpp 项目: enree/flyZ
QPair<int, int> Hive::move(const QPair<int, int> position, Direction direction)
{
    QPair<int, int> newPosition(position);
    switch (direction)
    {
    case N:
        --newPosition.second;
        break;
    case NE:
        ++newPosition.first;
        --newPosition.second;
        break;
    case E:
        ++newPosition.first;
        break;
    case SE:
        ++newPosition.first;
        ++newPosition.second;
        break;
    case S:
        ++newPosition.second;
        break;
    case SW:
        --newPosition.first;
        ++newPosition.second;
        break;
    case W:
        --newPosition.first;
        break;
    case NW:
        --newPosition.first;
        --newPosition.second;
        break;
    default:
        break;
    }
    return newPosition;
}
示例#28
0
void AnimatedSprite::Update(const sf::Vector2f& _position)
{
	sf::Vector2f newPosition(_position.x - frameWidth / 2, _position.y - frameHeight / 2);
	//setPosition(_position);
	setPosition(newPosition);

	if (currAnim != nullptr && !isPaused)
	{
		unsigned int animIndex = currFrame / 256;
		if (animIndex >= currAnim->getLength())
		{
			currFrame = 0;
			animIndex = 0;
		}
		unsigned int framePerRow = getTexture()->getSize().x / frameWidth;
		unsigned int frameIndex = currAnim->getFrame(animIndex);
		unsigned int frameWidthOffset = (frameIndex - framePerRow*(frameIndex / framePerRow))*frameWidth;
		unsigned int frameHeightOffset = (frameIndex / framePerRow) * frameHeight;
		++currFrame;

		setTextureRect(sf::IntRect(frameWidthOffset, frameHeightOffset, frameWidth, frameHeight));
	}
}
示例#29
0
void SnowEmitter::prepareParticles(){
    for(int i(0); i < density; ++i){

        // range -10.0 < x < 10.0
        float random1 = ((rand()%100)/100.0f)*20.0f - 10.0f;

        // range -20.0 < x < 0.0
        float random2 = ((rand()%100)/100.0f)*-20.0f;

        float random3 = 0.0f;
        if(rand()%10 == 1){
            random3 = ((rand()%100)/100.0f)*0.01f - 0.005;
        }

        glm::vec3 newPosition(random1, 1.0f, random2+5.0f);
        // newPosition += camera->getPosition();

        glm::vec3 velocity(random3, -0.02, 0.0f);
        glm::vec3 acceleration(0.0f, 0.0f, 0.0f);

        // Particle recycling!
        // Weird that the pointer must be explicitly set to 0, but crashes without this
        Particle* ptr = 0;
        if(particles.size() < maxParticles){
            ptr = new Particle(*billboard, shader);
            ptr->setEmissive(particle_texture);
        }
        if(particles.size() > 0 && particles[0]->isDead()){
            ptr = particles[0];
            particles.pop_front();
        }
        if(ptr){
            ptr->setInitialValues(newPosition, velocity, acceleration, 0.0f, lifespan, Particle::ScalingOption::SCALE_NONE, Particle::FadingOption::FADE_OUT_WITH_AGE);
            particles.push_back(ptr);
        }
    }
}
示例#30
0
void Player::frameUpdate (const float tslf)
{
    // Get the old (current) position.
    Ogre::Vector3 oldPosition = mPlayerNode->getPosition();

    // Calculate the components from the input.
    float forward = 0, right = 0, clockwise = 0;
    if (Core::mGraphicsCore->mUserInput->mKeyboard->isKeyDown(OIS::KC_W))
        forward -= 200 * tslf;
    if (Core::mGraphicsCore->mUserInput->mKeyboard->isKeyDown(OIS::KC_S))
        forward += 200 * tslf;
    if (Core::mGraphicsCore->mUserInput->mKeyboard->isKeyDown(OIS::KC_Q))
        right += 200 * tslf;
    if (Core::mGraphicsCore->mUserInput->mKeyboard->isKeyDown(OIS::KC_E))
        right -= 200 * tslf;
    if (Core::mGraphicsCore->mUserInput->mKeyboard->isKeyDown(OIS::KC_A))
        clockwise += 100 * tslf;
    if (Core::mGraphicsCore->mUserInput->mKeyboard->isKeyDown(OIS::KC_D))
        clockwise -= 100 * tslf;

    // rotate the player (so that we can calculate the new position with the new rotation applied).
    mPlayerNode->rotate(Ogre::Vector3::UNIT_Y, Ogre::Radian(Ogre::Degree(clockwise)));

    // Calculate the components of the translation.
    Ogre::Radian rot = mPlayerNode->getOrientation().getYaw(true);
    float zComponent = Ogre::Math::Cos(rot);
    float xComponent = Ogre::Math::Sin(rot);
    
    // Calculate the new position.
    Ogre::Vector3 newPosition(oldPosition.x + (xComponent * forward) + (xComponent * right),
                              0,
                              oldPosition.z + (zComponent * forward) + (zComponent * right));
    newPosition.y = Core::mWorld->getTerrainHeight(newPosition) + mPlayerHeight;

    // Apply this new position to the player.
    mPlayerNode->setPosition(newPosition);
}