Я пытаюсь создать игру поверх экрана в течение почти месяца, и я думал, что могу просто опубликовать свой текущий код и посмотреть, сможет ли кто-нибудь помочь. Я прочитал много уроков и просмотрел несколько хороших видеороликов, но мой код всегда кажется таким разным, что я сталкиваюсь с ошибками даже после долгих часов общения. То, что я пытаюсь создать, - это кнопка, которая возвращает вас к исходной странице (сделанной с помощью раскадровки) после столкновения между двумя моими спрайтами. Я могу сделать кнопку, которая вернет вас на начальный экран, но я бы хотел помочь с кодом, который не позволяет показывать до обнаружения столкновения и где объявить все для кнопки. По какой-то причине я всегда получаю ошибки, которые нельзя использовать и что они не используются правильно. Любая помощь приветствуется. Мой текущий код:Использование UIButton для игры по экрану
Viewcontroller.h
#import <UIKit/UIKit.h>
#import <SpriteKit/SpriteKit.h>
@interface ViewController : UIViewController
@end
Viewcontroller.m
#import "ViewController.h"
#import "MyScene.h"
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Configure the view.
SKView * skView = (SKView *)self.view;
skView.showsFPS = YES;
skView.showsNodeCount = YES;
// Create and configure the scene.
MyScene * scene = [MyScene sceneWithSize:skView.bounds.size];
scene.scaleMode = SKSceneScaleModeAspectFill;
scene.viewController = self;
// Present the scene.
[skView presentScene:scene];
}
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return UIInterfaceOrientationMaskAllButUpsideDown;
} else {
return UIInterfaceOrientationMaskAll;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
@end
MyScene.h
#import <SpriteKit/SpriteKit.h>
@interface MyScene : SKScene <SKPhysicsContactDelegate>
@property (strong, nonatomic) UIViewController *viewController;
@end
MyScene.m
#import "MyScene.h"
@interface MyScene()
@property (nonatomic) NSTimeInterval lastTimeSceneRefreshed;
@property (nonatomic) SKSpriteNode* squirrelSprite;
@property (nonatomic) SKSpriteNode* lightNut;
@property (nonatomic) SKSpriteNode* appleSprite;
@property NSTimeInterval lastTouch;
@property BOOL atFirstPosition;
@property CGPoint firstPosition;
@end
@implementation MyScene
static const int squirrelHitCategory = 1;
static const int nutHitCategory = 2;
- (instancetype)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.physicsWorld.contactDelegate = self;
[self buildBackground];
[self startScrolling];
_firstPosition = CGPointMake(self.frame.size.width * 0.817f, self.frame.size.height * .40f);
_squirrelSprite = [SKSpriteNode spriteNodeWithImageNamed:@"squirrel"];
_squirrelSprite.position = _firstPosition;
_atFirstPosition = YES;
_squirrelSprite.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:10];
_squirrelSprite.physicsBody.categoryBitMask = squirrelHitCategory;
_squirrelSprite.physicsBody.contactTestBitMask = nutHitCategory;
_squirrelSprite.physicsBody.collisionBitMask = nutHitCategory;
_squirrelSprite.physicsBody.affectedByGravity = NO;
self.physicsWorld.contactDelegate = self;
[self addChild:_squirrelSprite];
// Declare SKAction that waits 2 seconds
SKAction *wait = [SKAction waitForDuration:3.0];
// Declare SKAction block to generate the sprites
SKAction *createSpriteBlock = [SKAction runBlock:^{
SKSpriteNode *lightnut = [SKSpriteNode spriteNodeWithImageNamed:@"lightnut.png"];
BOOL heads = arc4random_uniform(100) < 50;
lightnut.position = (heads)? CGPointMake(257,600) : CGPointMake(50,600);
lightnut.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(200,160)];
lightnut.physicsBody.categoryBitMask = nutHitCategory;
lightnut.physicsBody.contactTestBitMask = squirrelHitCategory;
lightnut.physicsBody.collisionBitMask = squirrelHitCategory;
lightnut.physicsBody.affectedByGravity = NO;
self.physicsWorld.contactDelegate = self;
[self addChild: lightnut];
SKAction *moveNodeUp = [SKAction moveByX:0.0 y:-700.0 duration:1.3];
[lightnut runAction: moveNodeUp];
}];
// Combine the actions
SKAction *waitThenRunBlock = [SKAction sequence:@[wait,createSpriteBlock]];
// Lather, rinse, repeat
[self runAction:[SKAction repeatActionForever:waitThenRunBlock]];
}
return self;
}
- (void)update:(CFTimeInterval)currentTime {
// Updating background nodes
// We don't want to update backgrounds each frame (60 times per second)
// Once per second is enough. This will reduce CPU usage
if (currentTime - self.lastTimeSceneRefreshed > 1) {
[self backgroundNodesRepositioning];
self.lastTimeSceneRefreshed = currentTime;
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
// Check time since the last touch event
if (touch.timestamp-_lastTouch >= .9) {
// Allow touch
NSLog(@"greater than or equal to 3 seconds");
if (_atFirstPosition)
{
SKAction *moveNodeLeft = [SKAction moveByX:-207.8 y:0.0 duration:0.85];
[_squirrelSprite runAction: moveNodeLeft withKey:@"moveleft"];
} else {
SKAction *moveNodeRight = [SKAction moveByX:207.8 y:0.0 duration:0.85];
[_squirrelSprite runAction: moveNodeRight withKey:@"moveright"];
}
_atFirstPosition = !_atFirstPosition;
_squirrelSprite.xScale *= -1.0;
}
else {
// Ignore touch
NSLog(@"Seconds since last touch %g",touch.timestamp-_lastTouch);
}
// Store timestamp
_lastTouch = touch.timestamp;
}
-(void)didBeginContact:(SKPhysicsContact *)contact
{
NSLog(@"contact detected");
SKPhysicsBody *firstBody, *secondBody;
firstBody = contact.bodyA;
secondBody = contact.bodyB;
if(firstBody.categoryBitMask == squirrelHitCategory || secondBody.categoryBitMask == nutHitCategory)
{
}
}
-(void)goToHomeScreen {
[self.viewController.navigationController popToRootViewControllerAnimated:YES];
}
@end
Пожалуйста, дайте мне знать, если есть какая-либо другая информация, которую мне нужно добавить или что-нибудь, что я должен уточнить, спасибо!
Правильно ли зарегистрирован «контакт обнаружен»? Это когда вы хотите перейти на главный экран? –
Он регистрируется правильно, и я хочу небольшую коробку, в которой говорится, что игра завершена с помощью кнопки, чтобы вернуться на начальный экран после того, как она зарегистрирована. Спасибо! – Ryanc
В этом случае просто введите 'UIAlertController' в' didBeginContact: 'с помощью кнопки, которая запускает метод goToHomeScreen. –