When sliding sprite, if sprite disappears off the side, it will wrap around to the opposite side? - objective-c

When sliding sprite, if sprite disappears off the side, i want to make it wrap around to the opposite side but I do not know how to do this while the sprite is simultaneously being pushed off one side i want the other bit that you can't see to appear on the opposite side like a loop some sort of wormhole thing.
here is my code so far but it crashes and it only transports the sprite once the whole of the sprite disappears of the side. Loop also needs to run as an infinite loop until someone quits the app.
for (int i =0; i<16; ++i) {
MyNode *currentSprite = [c1array objectAtIndex:i];
if (currentSprite.contentSize.height>=320 || currentSprite.position.y-currentSprite.contentSize.height/2<=0 ){
MyNode *Bsprite = currentSprite;
MyNode *Tsprite = currentSprite;
Bsprite.scale = 1.0;
Tsprite.scale = 1.0;
if(currentSprite.position.y >=253){
Bsprite.position = ccp(currentSprite.position.x,-35);
[self addChild:Bsprite];
Bsprite.visible = TRUE;
}
if (currentSprite.position.y <=0) {
Tsprite.position = ccp(currentSprite.position.x,324);
[self addChild:Tsprite];
Tsprite.visible = TRUE;
}
MyNode *isChanging;
if ((Tsprite.visible == TRUE && currentSprite.visible == TRUE) || (Bsprite.visible == TRUE && currentSprite.visible == TRUE)) {
isChanging = TRUE;
}
if (isChanging == FALSE) {
[self removeChild:Tsprite cleanup:YES];
[self removeChild:Bsprite cleanup:YES];
}
}
}

It is not possible to do with one sprite. But you can have two sprites. In common situation when your sprite is sliding along the screen only one sprite will be visible. But when it reaches the border the second one will be visible too. When the second one will completely enter the screen - remove (or hide) the first one.
The best way to implement this is to create a CCNode subclass that will contain first and second sprite and will swap them if required. In this way all your logic will be very simple. You will just work with one CCNode (subclass) and will not think about swaping sprites - it will be done automatically by your class
EDIT
#interface MyNode : CCNode
{
CCSprite *sprite1;
CCSprite *sprite2;
CCSprite *currentSprite;
bool isChanging; //indicates that now two sprites are visible
}
#end

Related

How to detect which CALayer was clicked on?

I'm having a problem detecting which CALayer is being clicked on, as these CALayers have a constant CABasicAnimation moving the x and y positions.
My current code is as follows:
-(void)mouseUp:(NSEvent *)theEvent
{
CGPoint pointInView = NSPointToCGPoint([self convertPoint:[theEvent locationInWindow]fromView:nil]);
CALayer* clickedOn = [(CALayer*) self.layer hitTest:[self.layer convertPoint:pointInView toLayer:self.layer.superlayer]];
int selectedContact = -1;
for (int i = 0; i < [contactLayers count]; i++) {
CALayer* presentationLayer = [contactLayers[i] presentationLayer];
if (presentationLayer == clickedOn) {
selectedContact = i;
break;
}
}
if(selectedContact == -1)
return; //no contact selected;
CALayer* selectedContactLayer = contactLayers[selectedContact];
[selectedContactLayer removeFromSuperlayer];
}
contactLayers is an NSMutableArray containing all the possible CALayers the user can click on.
Every time this runs, i always seems to end up staying -1. I'm using presentationLayer since the CALayers have a CABasicAnimation applied to them. I also tried modelLayer, but this only works if you click on the initial location of each layer.
So just a recap: I have an NSMutableArray of CALayers that all have a CABasicAnimation applied, this array is called contactLayers. When the user clicks on a layer, I need to know what layer they clicked on by setting the index to the appropriate value in the array.
Compute 'clickedOn' by hit testing 'self.layer.presentationLayer', not 'self.layer'

Xcode, SpriteKit: Rotating a whole scene, and editing properties of a sprite inside an array

I'm using Xcode, SpriteKit to create a game. 2 questions:
1) I need the whole scene to rotate whenever a function is called:
- (void)mouseClick {
// RotateWholeScene somehow
}
I know about rotating a sprite by changing its zrotation, but changing scene.zrotation doesn’t work.
Also, some things in the scene need to stay in the same position, like the score, etc.
I’d prefer it if there is a way which I can rotate the whole scene as if the camera view has changed, as there are calculations (like falling objects) which would be much easier to do if they aren’t needed to be changed in the code.
2) Right now the program creates a sprite each frame, and places the sprite into an array (which I declared at the start).
NSMutableArray *SomeArray = [NSMutableArray arrayWithObjects: nil];
And later on in the code:
- (void)CalledEachFrame {
[self addChild: SomeSprite];
[SomeArray addObject: SomeSprite];
}
Elsewhere in the code, I need:
- (void)AlsoCalledEachFrame {
for (int i; i < X; i++) {
SomeArray[i].position = A;
}
}
This (and several other attempts) doesn't work, and I get an error:
***EDIT: My bad. In the image, I showed, I set the position to an integer rather than a CGPoint. Nevertheless, the same error occur even if I put a CGPoint instead of those 99s.
You asking two questions at once here. I should discourage that. Nevertheless, here goes:
1) I faced a similar problem and my solution to this problem was putting the scene nodes and the hud nodes each in a separate child nodes of the SKScene subclass, like so:
#interface SKSceneSubclass : SKScene
// ...
#property (strong, nonatomic, readonly) SKNode *sceneContents;
#property (strong, nonatomic, readonly) SKNode *hud;
#end
In the scene initializer, I'd put:
- (instancetype)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.sceneContents = [SKNode new];
[self addChild:self.sceneContents];
self.hud = [SKNode new];
[self addChild:self.hud];
self.hud.zPosition = 20.f; // ensures the hud on top of sceneContents
// your custom stuff
// ...
}
return self;
}
This requires you to decide upon adding child nodes which node (sceneContents or hud) will be their parent.
[self.sceneContents addChild:newSprite];
[self.hud addChild:someCoolHudButton];
Then, you can just run [SKAction rotateByAngle:angle duration:duration] on the sceneContents node. The hud and its children will not be affected. I am currently employing this method to move and zoom sceneContents while having a stationary HUD which behaves as it should.
2) The problem is that you are not telling the compiler the item you're accessing is an SKNode object, so the compiler does not allow you to access the position property. If you are certain only the array will only contain SKNodes or subclasses thereof, use the forin iterator method.
for (<#type *object#> in <#collection#>) {
<#statements#>
}
In your case, it would look like this.
CGPoint newPosition = CGPointMake(x, y);
for (SKNode *node in SomeArray) {
node.position = newPosition;
}
You can manually rotate the view with this code:
CGAffineTransform transform = CGAffineTransformMakeRotation(-0.1); // change value to desires angle
self.view.transform = transform;

How to trick an OS X app into thinking the mouse is a finger?

I'm writing a Mac app that contains a collection view. This app is to be run on a large touchscreen display (55" EP series from Planar). Due to hardware limitation, the touchscreen doesn't send scroll events (or even any multitouch events). How can I go about tricking the app into thinking a "mousedown+drag" is the same as a "mousescroll"?
I got it working halfway by subclassing NSCollectionView and implementing my own NSPanGestureRecognizer handler in it. Unfortunately the result is clunky and doesn't have the feeling of a normal OS X scroll (i.e., the velocity effect at the end of a scroll, or scroll bounce at the ends of the content).
#implementation UCTouchScrollCollectionView
...
- (IBAction)showGestureForScrollGestureRecognizer:(NSPanGestureRecognizer *)recognizer
{
CGPoint location = [recognizer locationInView:self];
if (recognizer.state == NSGestureRecognizerStateBegan) {
touchStartPt = location;
startOrigin = [(NSClipView*)[self superview] documentVisibleRect].origin;
} else if (recognizer.state == NSGestureRecognizerStateEnded) {
/* Some notes here about a future feature: the Scroll Bounce
I don't want to have to reinvent the wheel here, but it
appears I already am. Crud.
1. when the touch ends, get the velocity in view
2. Using the velocity and a constant "deceleration" factor, you can determine
a. The time taken to decelerate to 0 velocity
b. the distance travelled in that time
3. If the final scroll point is out of bounds, update it.
4. set up an animation block to scroll the document to that point. Make sure it uses the proper easing to feel "natural".
5. make sure you retain a pointer or something to that animation so that a touch DURING the animation will cancel it (is this even possible?)
*/
[self.scrollDelegate.pointSmoother clearPoints];
refreshDelegateTriggered = NO;
} else if (recognizer.state == NSGestureRecognizerStateChanged) {
CGFloat dx = 0;
CGFloat dy = (startOrigin.y - self.scrollDelegate.scrollScaling * (location.y - touchStartPt.y));
NSPoint scrollPt = NSMakePoint(dx, dy);
[self.scrollDelegate.pointSmoother addPoint:scrollPt];
NSPoint smoothedPoint = [self.scrollDelegate.pointSmoother getSmoothedPoint];
[self scrollPoint:smoothedPoint];
CGFloat end = self.frame.size.height - self.superview.frame.size.height;
CGFloat threshold = self.superview.frame.size.height * kUCPullToRefreshScreenFactor;
if (smoothedPoint.y + threshold >= end &&
!refreshDelegateTriggered) {
NSLog(#"trigger pull to refresh");
refreshDelegateTriggered = YES;
[self.refreshDelegate scrollViewReachedBottom:self];
}
}
}
A note about this implementation: I put together scrollScaling and pointSmoother to try and improve the scroll UX. The touchscreen I'm using is IR-based and gets very jittery (especially when the sun is out).
In case it's relevant: I'm using Xcode 6 beta 6 (6A280e) on Yosemite beta (14A329r), and my build target is 10.10.
Thanks!
I managed to have some success using an NSPanGestureRecognizer and simulating the track-pad scroll wheel events. If you simulate them well you'll get the bounce from the NSScrollView 'for free'.
I don't have public code, but the best resource I found that explained what the NSScrollView expects is in the following unit test simulating a momentum scroll. (See mouseScrollByWithWheelAndMomentumPhases here).
https://github.com/WebKit/webkit/blob/master/LayoutTests/fast/scrolling/latching/scroll-iframe-in-overflow.html
The implementation of mouseScrollByWithWheelAndMomentumPhases gives some tips on how to synthesize the scroll events at a low level. One addition I found I needed was to actually set an incrementing timestamp in the event in order to get the scroll-view to play ball.
https://github.com/WebKit/webkit/blob/master/Tools/WebKitTestRunner/mac/EventSenderProxy.mm
Finally, in order to actually create the decaying velocity, I used a POPDecayAnimation and tweaked the velocity from the NSPanGestureRecognizer to feel similar. Its not perfect but it does stay true to NSScrollView's bounce.
I have a (dead) project on Github that does this with an NSTableView, so hopefully it will work well for an NSCollectionView.
Disclaimer: I wrote this while I was still learning GCD, so watch for retain cycles... I did not vet what I just posted for bugs. feel free to point any out :) I just tested this on Mac OS 10.9 and it does still work (originally written for 10.7 IIRC), not tested on 10.10.
This entire thing is a hack to be sure, it looks like it requires (seems to anyway) asynchronous UI manipulation (I think to prevent infinite recursion). There is probably a cleaner/better way and please share it when you discover it!
I havent touched this in months so I cant recall all the specifics, but the meat of it surely is in the NBBTableView code, which will paste snippets of.
first there is an NSAnimation subclass NBBScrollAnimation that handles the "rubber band" effect:
#implementation NBBScrollAnimation
#synthesize clipView;
#synthesize originPoint;
#synthesize targetPoint;
+ (NBBScrollAnimation*)scrollAnimationWithClipView:(NSClipView *)clipView
{
NBBScrollAnimation *animation = [[NBBScrollAnimation alloc] initWithDuration:0.6 animationCurve:NSAnimationEaseOut];
animation.clipView = clipView;
animation.originPoint = clipView.documentVisibleRect.origin;
animation.targetPoint = animation.originPoint;
return [animation autorelease];
}
- (void)setCurrentProgress:(NSAnimationProgress)progress
{
typedef float (^MyAnimationCurveBlock)(float, float, float);
MyAnimationCurveBlock cubicEaseOut = ^ float (float t, float start, float end) {
t--;
return end*(t * t * t + 1) + start;
};
dispatch_sync(dispatch_get_main_queue(), ^{
NSPoint progressPoint = self.originPoint;
progressPoint.x += cubicEaseOut(progress, 0, self.targetPoint.x - self.originPoint.x);
progressPoint.y += cubicEaseOut(progress, 0, self.targetPoint.y - self.originPoint.y);
NSPoint constraint = [self.clipView constrainScrollPoint:progressPoint];
if (!NSEqualPoints(constraint, progressPoint)) {
// constraining the point and reassigning to target gives us the "rubber band" effect
self.targetPoint = constraint;
}
[self.clipView scrollToPoint:progressPoint];
[self.clipView.enclosingScrollView reflectScrolledClipView:self.clipView];
[self.clipView.enclosingScrollView displayIfNeeded];
});
}
#end
You should be able to use the animation on any control that has an NSClipView by setting it up like this _scrollAnimation = [[NBBScrollAnimation scrollAnimationWithClipView:(NSClipView*)[self superview]] retain];
The trick here is that the superview of an NSTableView is an NSClipView; I dont know about NSCollectionView, but I suspect that any scrollable control uses NSClipView.
Next here is how the NBBTableView subclass makes use of that animation though the mouse events:
- (void)mouseDown:(NSEvent *)theEvent
{
_scrollDelta = 0.0;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
if (_scrollAnimation && _scrollAnimation.isAnimating) {
[_scrollAnimation stopAnimation];
}
});
}
- (void)mouseUp:(NSEvent *)theEvent
{
if (_scrollDelta) {
[super mouseUp:theEvent];
// reset the scroll animation
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSClipView* cv = (NSClipView*)[self superview];
NSPoint newPoint = NSMakePoint(0.0, ([cv documentVisibleRect].origin.y - _scrollDelta));
NBBScrollAnimation* anim = (NBBScrollAnimation*)_scrollAnimation;
[anim setCurrentProgress:0.0];
anim.targetPoint = newPoint;
[anim startAnimation];
});
} else {
[super mouseDown:theEvent];
}
}
- (void)mouseDragged:(NSEvent *)theEvent
{
NSClipView* clipView=(NSClipView*)[self superview];
NSPoint newPoint = NSMakePoint(0.0, ([clipView documentVisibleRect].origin.y - [theEvent deltaY]));
CGFloat limit = self.frame.size.height;
if (newPoint.y >= limit) {
newPoint.y = limit - 1.0;
} else if (newPoint.y <= limit * -1) {
newPoint.y = (limit * -1) + 1;
}
// do NOT constrain the point here. we want to "rubber band"
[clipView scrollToPoint:newPoint];
[[self enclosingScrollView] reflectScrolledClipView:clipView];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NBBScrollAnimation* anim = (NBBScrollAnimation*)_scrollAnimation;
anim.originPoint = newPoint;
});
// because we have to animate asyncronously, we must save the target value to use later
// instead of setting it in the animation here
_scrollDelta = [theEvent deltaY] * 3.5;
}
- (BOOL)autoscroll:(NSEvent *)theEvent
{
return NO;
}
I think that autoscroll override is essential for good behavior.
The entire code is on my github page, and it contains several other "touch screen" emulation tidbits, if you are interested, such as a simulation for the iOS springboard arrangeable icons (complete with "wiggle" animation using NSButtons.
Hope this helps :)
Edit: It appears that constrainScrollPoint: is deprecated in OS X 10.9. However, It should fairly trivial to reimplement as a category or something. Maybe you can adapt a solution from this SO question.

How to z-rotate two SKSpriteNodes together as if one?

How can I group two SKSpriteNodes together so that I can z-rotate them as if they are one? Let's say one SKSpriteNode is a rope and the other is a ball attached to the end of the rope. How can I make it look like they swing together? What would be the SKAction to do this?
Two options:
Put them both in a SKNode and rotate the SKNode (around a certain anchor point)
SKNode *container = [[SKNode alloc] init];
[container addChild:ballSprite];
[container addChild:ropeSprite];
container.zRotation = someValue;
Or rotate them separately and them move them so it looks as if they were rotated together.
Probably not the most elegant solution but here is how i have added SKSpriteNodes to a SKNode (container). containerArray contains the nodes that should be added. The newSpriteName (NSString) is used when deciding if the sprite is displayed with it's front side or back side.
// Add a container
_containerNode = [SKNode node];
_containerNode.position = _theParentNodePosition;
_containerNode.name = #"containerNode";
[_background addChild:_containerNode];
for (SKNode *aNode in containerArray) {
if (![aNode.name isEqualToString:#"background"] && ![aNode.name isEqualToString:#"title1"] && ![aNode.name isEqualToString:#"title2"]) {
// Check if "back" sprite should be added or the front face
if ([[aNode.name substringFromIndex:[aNode.name length] - 1] isEqualToString:#"b"]) {
newSpriteName = #"back";
} else {
newSpriteName = aNode.name;
}
// Prepare the new node
SKSpriteNode *newNode = [SKSpriteNode spriteNodeWithImageNamed:newSpriteName];
newNode.name = aNode.name;
newNode.zPosition = aNode.zPosition;
newNode.position = CGPointMake(aNode.position.x - _theParentNodePosition.x, aNode.position.y - _theParentNodePosition.y);
// Delete the old node
SKNode *deleteNode = [_background childNodeWithName:aNode.name];
[deleteNode removeFromParent];
// Add the new node
[_containerNode addChild:newNode];
}
}
And then do a rotation as DrummerB suggested

Cocos2D Infinite Background Picture

I'm curious as to how to create an infinite background in cocos2d. For example lets say I was building an app with a man running from left to right, and I want him to run infinitely. Well in that case I would have to have an endless background so the man could keep running. I've continuously searched on this matter and have found nothing that actually works.
Any types of suggestions, answers, and tips are much appreciated.
Thanks
Try This:
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define MM_BG_SPEED_DUR ( IS_IPAD ? (6.0f) : (2.0f) )
-(void)onEnter
{
[super onEnter];
[self initBackground];
[self schedule: #selector(tick:)];
}
-(void)initBackground
{
NSString *tex = #"BG/Background.png";//[self getThemeBG];
mBG1 = [CCSprite spriteWithFile:tex];
mBG1.position = ccp(s.width*0.5f,s.height*0.5f);
[self addChild:mBG1 z:LAYER_BACKGROUND];
mBG2 = [CCSprite spriteWithFile:tex];
mBG2.position = ccp(s.width+s.width*0.5f,s.height*0.5f);
mBG2.flipX = true;
[self addChild:mBG2 z:LAYER_BACKGROUND];
}
-(void)scrollBackground:(ccTime)dt
{
CGSize s = [[CCDirector sharedDirector] winSize];
CGPoint pos1 = mBG1.position;
CGPoint pos2 = mBG2.position;
pos1.x -= MM_BG_SPEED_DUR;
pos2.x -= MM_BG_SPEED_DUR;
if(pos1.x <=-(s.width*0.5f) )
{
pos1.x = pos2.x + s.width;
}
if(pos2.x <=-(s.width*0.5f) )
{
pos2.x = pos1.x + s.width;
}
mBG1.position = pos1;
mBG2.position = pos2;
}
-(void)tick:(ccTime)dt
{
[self scrollBackground:dt];
}
The easiest way would be to include two background images that mesh seamlessly together. (CCSprite would work fine for this) In your update method as soon as the first background is completely off of the screen move it back to the other side of the screen directly next to the second background and continually move both background images. Repeat this process for the second background as well.
CCTMXTiledMap can help you, but I'm afraid that you must handle end of map and add another manually. Check this tutorials how to use tiled maps in side-scrolling games, hope it will be useful for you:
http://www.raywenderlich.com/15230/how-to-make-a-platform-game-like-super-mario-brothers-part-1
Try this. It is very easily to implement and works well. Just follow the tutorial on the read me.