iPad:como mover um sprite deslizando-o e continuar de acordo com a velocidade de deslizamento

StackOverflow https://stackoverflow.com/questions/3235428

Pergunta

Eu tenho um sprite (imagem de uma bola). Posso movê-lo usando toque e movimento.Também identifiquei a taxa de mudança de localização (eixo x, eixo y) desse sprite dependendo do período de deslizamento.

Agora preciso continuar esse sprite indo de acordo com sua velocidade e direção.Aqui está meu código-

Touch Event

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {

  CGPoint location = [touch locationInView: [touch view]];
  CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];

  self.touchStartTime = [event timestamp];
  self.touchStartPosition = location;

  if (YES == [self isItTouched:self.striker touchedAt:convertedLocation]) {
    self.striker.isInTouch = YES;
  }

  return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {

  CGPoint location = [touch locationInView: [touch view]];
  CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];

  self.touchLastMovedTime = [event timestamp];
  self.touchMovedPosition = convertedLocation;


  if(self.striker.isInTouch == YES){
    self.striker.position = self.touchMovedPosition;
  }

}
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {

  CGPoint location = [touch locationInView: [touch view]];
  CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];

  self.touchEndTime = [event timestamp];
  self.touchEndPosition = location;

  if( self.striker.isInTouch == YES 
    && ( self.touchEndTime - self.touchLastMovedTime ) <= MAX_TOUCH_HOLD_DURATION )
  {
    float c = sqrt( pow( self.touchStartPosition.x - self.touchEndPosition.x, 2 ) 
        + pow( self.touchStartPosition.y - self.touchEndPosition.y, 2 ) );

    self.striker.speedx =  ( c - ( self.touchStartPosition.y - self.touchEndPosition.y ) ) 
                         / ( ( self.touchEndTime - self.touchStartTime ) * 1000 );

    self.striker.speedy =  ( c - ( self.touchStartPosition.x - self.touchEndPosition.x ) ) 
             / ( ( self.touchEndTime -   self.touchStartTime ) * 1000 );

    self.striker.speedx *= 4;
    self.striker.speedy *= 4;

    self.striker.isInTouch = NO;
    [self schedule:@selector( nextFrame ) interval:0.001];

  }

}

Scheduled Method to move Sprite

- (void) nextFrame {

  [self setPieceNextPosition:self.striker];
  [self adjustPieceSpeed:self.striker];

  if( abs( self.striker.speedx ) <= 1 && abs( self.striker.speedy ) <= 1 ){
    [self unschedule:@selector( nextFrame )];
  }
}

SET next Position

- (void) setPieceNextPosition:(Piece *) piece{

  CGPoint nextPosition;
  float tempMod;
  tempMod = ( piece.position.x + piece.speedx ) / SCREEN_WIDTH;
  tempMod = (tempMod - (int)tempMod)*SCREEN_WIDTH;
  nextPosition.x = tempMod;

  tempMod = ( piece.position.y + piece.speedy ) / SCREEN_HEIGHT;
  tempMod = (tempMod - (int)tempMod)*SCREEN_HEIGHT;
  nextPosition.y = tempMod;

  piece.position = nextPosition;
}

Set new Speed

- (void) adjustPieceSpeed:(Piece *) piece{

  piece.speedx =(piece.speedx>0)? piece.speedx-0.05:piece.speedx+0.05;
  piece.speedy =(piece.speedy>0)? piece.speedy-0.05:piece.speedy+0.05;
}

Porém, atualmente estou usando a técnica de ajuste de velocidade estática, mas espero torná-la dinâmica dependendo da velocidade inicial (agradeço qualquer ideia)

Foi útil?

Solução 2

obrigado @todos.Eu tenho minha solução conforme abaixo-

//in adjustSpeed method
  piece.speedx -= piece.speedx * DEACCLERATION_FACTOR;
  piece.speedy -= piece.speedy * DEACCLERATION_FACTOR;

//and simply, free the sprite to move from ccTouchMoved method not ccTouchEnd
  if(self.striker.isInTouch == YES && distance_passed_from_touch_start>=a_threashold){
    //calculate speed and position here as it was in ccTouchEnd method
    self.striker.isInTouch = NO;
    [self schedule:@selector( nextFrame ) interval:0.001];

  }

Outras dicas

Parece que você está bem perto.Você está programando um seletor na extremidade de toque, calculando a velocidade e movendo o sprite de acordo com essa velocidade até que ele diminua, para que todas as peças mecânicas estejam lá.

O que parece duvidoso é a física.Por exemplo, você está fazendo algumas coisas estranhas com a velocidade para desacelerar a bola que não parecerão nada realistas.

O que você quer fazer é encontrar o "vetor de velocidade" do sprite quando o dedo é levantado.Embora você possa tentar obter uma velocidade instantânea para isso, descobri que funciona melhor amostrar alguns ciclos atrás e calcular a média deles para obter a velocidade final.

Então, depois de obter esse vetor (será parecido com uma velocidade xey, como você tem agora), você deseja diminuir a velocidade fazendo algo assim (pseudocódigo não testado adiante):

 float speed = sqrt( speedx * speedx + speedy * speedy );
 if (speed == 0) {
     // kill motion here, unschedule or do whatever you need to
 }
 // Dampen the speed.
 float newSpeed = speed * .9;
 if (newSpeed < SOME_THRESHOLD) newSpeed = 0;
 speedx = speedx * newSpeed / speed;
 speedy = speedy * newSpeed / speed;
 //  Move sprite according to the new speed

Isso manterá a bola na mesma direção de quando foi lançada, diminuindo gradualmente a velocidade até parar.Para obter mais informações, especialmente se você quiser saltar ou algo assim, pesquise no Google uma introdução à álgebra vetorial.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top