2d Car steering algorithm with left and right? - iphone

I'm pretty new to programming and have only "programmed" apps in the game creator Gamesalad before. I have a game on the Appstore that i want to update because it is really buggy and slow. I would be glad if someone could help me putting this piece of code together. The car is basically constantly moving forward and their is no break button. The problem i seem to not be able to figure out it that it needs to work whatever direction the car is moving.
// User pressed start game button
- (IBAction)Begin:(id)sender {
timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:#selector(movement1) userInfo:nil repeats:YES];
Hide.hidden = YES;
}
// BOOL for left or right
- (IBAction)Leftdown1:(id)sender {
NSLog(#"%hhd",left1);
left1 = YES;
}
- (IBAction)Left1up:(id)sender {
NSLog(#"%hhd",left1);
left1 = NO;
}
- (IBAction)Right1down:(id)sender {
right1 = YES;
}
- (IBAction)Right1up:(id)sender {
right1 = NO;
}
// movement1 getting called every 0.01 seconds
-(void)movement1{
if (left1) {
//here i don't know what to do. I suppose i need to use cosines. The code below is just me testing.
point1 = CGPointMake(point1.x-1, point1.y-1);
} else {
point1 = CGPointMake(point1.x+1, point1.y+1);
}
if (right1) {
point1 = CGPointMake(point1.x-1, point1.y-1);
} else {
point1 = CGPointMake(point1.x+1, point1.y+1);
}
car.center = point1;
}

Related

what is the best way to code continuous X and Y movement of a sprite node in swift

I am creating my first sprite kit game and i am having difficulty coding my hero's movement. Here is how i coded my hero's movement in objective-c in a single view application using touch down and touch up inside IBactions. I am trying to repeat the same results in a sprite kit game in swift.
-(IBAction)LeftArrowTapped:(id)sender; {
[self heroMovementTimerMethodLeft];
}
-(IBAction)RightArrowTapped:(id)sender; {
[self heroMovementTimerMethodRight];
}
-(IBAction)TouchEndedLeft:(id)sender; {
[heroMovementTimerLeft invalidate];
}
-(IBAction)TouchEndedRight:(id)sender; {
[heroMovementTimerRight invalidate];
}
-(void)heroMovementTimerMethodLeft {
heroMovementTimerLeft = [NSTimer
scheduledTimerWithTimeInterval:speedOfhero target:self
selector:#selector(heroMovementLeft) userInfo:nil repeats:YES];
}
-(void)heroMovementTimerMethodRight {
heroMovementTimerRight =
[NSTimerscheduledTimerWithTimeInterval:speedOfhero target:self
selector:#selector(heroMovementRight) userInfo:nil repeats:YES];
}
-(void)heroMovementLeft{
hero.center = CGPointMake(hero.center.x -.5, hero.center.y );
}
-(void)heroMovementRight{
hero.center = CGPointMake(hero.center.x +.5, hero.center.y );
}
-(void)enemyMovementTimerMethod {
enemyMovementTimer =
[NSTimerscheduledTimerWithTimeInterval:speedOfEnemy target:self
selector:#selector(enemyMovement) userInfo:nil repeats:YES];
}
I understand that in sprite kit i will have to replace my IBactions with touchesBegan and touchesEnded methods but how do i repeat the coded results in swift. Here is how i am trying now
let heroMovementLeft = SKAction.moveToX(self.size.width - 5,
duration: 3)
But i get an error, i have also tried
let heroMovementLeft = CGPointMake(hero.position.x -5 ,
hero.position.y)
I apologize i am very new to swift and sprite kits
Using SKActions like you trying is fine.
Are you actually running the action, because from your code it seems like you are not.
let heroMovementLeft = SKAction.moveToX(self.size.width - 5,duration: 3)
hero.runAction(heroMovementLeft) // This is missing in your code example

how to move simple view in self boundary of simulator of iphone infinitely without animation in objective c?

I want to move my UIView of size (x=50,y=50) in the boundary of simulator screen means rectangular without animation infinitely.
To moving view continuously in your simulator boundary you have to put logic there is no predefined method without animation. if you are using animation then below given link is useful. How to repeat animation from current state not from startingstate? or without animation the below code will help you.
And yes please note that **
pos
** is a object of CGPoint class and you don't have to allocate it simply declare in interface.
- (void)viewDidLoad
{
pos = v1.center;
NSLog(#"POSITION === %f",pos.x);
[NSTimer scheduledTimerWithTimeInterval:0.05
target:self
selector:#selector(rotateBoundary)
userInfo:nil
repeats:YES];
[super viewDidLoad];
//[self performSelector:#selector(rotateBoundary) withObject:self afterDelay:5.0];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)rotateBoundary
{
if (pos.x>=20 && pos.x<=290 && pos.y==25)
{
NSLog(#"Top left to right.");
pos.x+=5;
v1.center = pos;
NSLog(#"pos.x === %f",pos.x);
}
if(pos.x >= 290 && pos.y<=430)
{
NSLog(#"Right top to down.");
pos.y+=5;
v1.center = pos;
NSLog(#"pos.y === %f",pos.y);
}
if(pos.y == 430 && pos.x>=20)
{
NSLog(#"Down right to left.");
pos.x-=5;
v1.center = pos;
NSLog(#"pos.x === %f",pos.x);
}
if (pos.x <= 20 && pos.y>=25)
{
NSLog(#"Down left to top.");
pos.y-=5;
v1.center = pos;
NSLog(#"pos.y === %f",pos.y);
}
}

Sprite jumping around when i use resumeSchedulerAndActions

Ok I am attempting some AI stuff here and I have been following some Ray Wenderlich tutorials. I have some strange behavior going on. Maybe I am just doing this all wrong... but here you go. When a sprite is within 75 pixels of the target it switches to the Defending AIState and i call pauseSchedulerAndActions and set it to a predetermined safe spot via getDefensePosition method. What I am trying to do is after 2 seconds resume the actions so the sprite will move around again. so I call resumeSchedulerAndActions. Now this just goes through the getDefenseMethod and it moves te sprite between these three places but this is the strange behavior i have two slog calls one before getDefenseMethod and one after the sprite is jumping around from the center of the screen then back to the new spawnPoint:
2013-03-04 20:08:14.897 10-8[2629:c07] before: {217.533, 177.32}
2013-03-04 20:08:14.898 10-8[2629:c07] spawnPoint 1
2013-03-04 20:08:14.899 10-8[2629:c07] after: {100, 100}
dont understand why it is doing that. Why does it not just start from the position it was in?
- (void)execute:(GangMembers *)player {
// Check if should change state
NSArray * enemies = [player.layer enemiesOutsideRange:75 ofPlayer:player];
if (enemies.count > 0) {
NSLog(#"outside range 75");
[player changeState:[[Attacking alloc] init]];
return;
}
[player.layer setPlayer:player attacking:NO];
// Make build decision
[player.layer unschedule:#selector(shoot:)];
[player pauseSchedulerAndActions];
NSLog(#"before: %#", NSStringFromCGPoint(player.position));
[self getDefensePosition];
player.position = spawnPoint;
NSLog(#"after: %#", NSStringFromCGPoint(player.position));
[player performSelector:#selector(resumeSchedulerAndActions) withObject:player afterDelay:2];
}
- (void)getDefensePosition {
// CGSize winSize = [CCDirector sharedDirector].winSize;
int spawnChoice = arc4random() % 3;
spawnPoint = ccp(100, 100);
if(spawnChoice == 0){
spawnPoint = ccp(100, 100);
NSLog(#"spawnPoint 1");
}
else if(spawnChoice == 1){
spawnPoint = ccp(100, 200);
NSLog(#"spawnPoint 2");
}
else {
spawnPoint = ccp(100, 300);
NSLog(#"spawnPoint 3");
}
}
FWIW, I suspect your player object has some CCMove type of actions (which you are pausing). Even though you change the position while paused, when the action resumes, the action sets the position to its current state (startPosition, endPosition, duration, time elapsed since start), which may be quite different from the position you set during the pause.
not certain of your object model/class structure, but something like this:
[player stopAllActions];
player.position = spawnPoint;
[player runAction: [CCSequence actions:
[CCDelayTime actionWithDuration:2.0],
[CCMoveTo actionWithDuration:arc4random()%5+1 position: randomPoint],
[CCCallBlock actionWithBlock:^{ [self performSelector:#selector(moveRandom:) withObject:s afterDelay:0.5]; }],
nil]
];
this way, you recreate a moveto action that will be executed from spawnPoint, and your player.position is not in contention with a running action. Written from memory, you mileage may vary :)

UIView in a MapView disappears

I have a problem with google maps in ios. I have a screen with the MapView and I am drawing some annotations (polygones dispalying zones on the streets). If somebody taps the zone it gets selected a button shows up and the user can press it to start a transaction. He has to hold the button for 2s and in this time a small view with a progress bar is shown to indicate that the user has to hold it till it comes to end. This works fine. However sometimes after playing a bit following problem appears:
The View with the progress bar show up but disappears before it reaches the end. If try next time everything works smoothly. Here is the code that matters, I think:
- (IBAction)starButtonTouched:(id)sender {
self.progressLabel.text = [NSLocalizedString(#"Please hold", nil) uppercaseString];
if (!self.currentVehicle) return;
self.progressBar.hidden = NO;
self.progressBarBackground.hidden = NO;
self.progressBar.progress = 0;
[self performSelector:#selector(_updateProgress) withObject:nil afterDelay:kVTMainButtonPressDuration/kVTMainProgressSteps];
}
- (IBAction)startButtonReleased:(id)sender {
NSLog(#"StartButton released - progress bar will be hidden");
self.progressBar.hidden = YES;
self.progressBarBackground.hidden = YES;
}
- (void) _updateProgress {
if (self.progressBar.hidden) return;
/*
* update progress bar
*/
float actual = [self.progressBar progress];
if (actual < 1) {
self.progressBar.progress += 1.0/kVTMainProgressSteps;
[NSTimer scheduledTimerWithTimeInterval:kVTMainButtonPressDuration/kVTMainProgressSteps target:self
selector:#selector(_updateProgress) userInfo:nil repeats:NO];
/*
* if it has ended start the transaction
*/
} else {
ASLogInfo(#"Starting");
if (!self.currentVehicle) return;
[self.service startParking:self.currentVehicle zone:self.selectedZone callback:^(VTTransaction *transaction) {
[self loadCurrentTransaction];
}];
}
}
Does anybody have an idea what and why causes the View to disappear? Thanks a lot.
Bye,
Filip

Simple Game - adding a countdown after scoring

I am creating a simple tennis game in Objective-C. Currently, when the player or the computer scores, it gives a message "tap to begin" and that releases the ball (it's a bit awkward to have your thumb on the racquet and another thumb to tap it to begin).
How do I add a timer into my game so that I don't have to tap after every score?
(This code is the resetting method when there is a new game and when there is a score)
{
self.gameState = kGameStatePaused;
ball.center = self.view.center;
if(newGame)
{
if(computerScoreValue > playerScoreValue)
{
tapToBegin.textAlignment = UITextAlignmentCenter;
tapToBegin.text = #"Computer Wins!";
AudioServicesPlaySystemSound(booFileID);
}
else
{
tapToBegin.textAlignment = UITextAlignmentCenter;
tapToBegin.text = #"You Win!";
AudioServicesPlaySystemSound(clappingFileID);
}
computerScoreValue = 0;
playerScoreValue = 0;
}
else
{
tapToBegin.textAlignment = UITextAlignmentCenter;
tapToBegin.text = #"Tap to Begin";
}
playerScore.text = [NSString stringWithFormat:#"%d",playerScoreValue];
computerScore.text = [NSString stringWithFormat:#"%d",computerScoreValue];
}
NSTimer should work. If you're curious take a look at CADisplayLink too.