How to set the location of a CC3Node in a layer? - cocos2d-iphone

I've not been able to find this in the docs.
I've got a CC3Node (myNode) and my layer has the callbacks for touchDown & touchMoved events all of which works, so far. I'm trying to drag myNode around the screen, preferably using screen coordinates.
How do I set myNode's location relative to screen (layer) coordinates?

Ok, I finally tracked this down, although the pieces were a bit scattered around in multiple posts. My final solution looked something like this:
MyWorld.m:
// Error checking and misc removed
- (void) addBackgroundForProjection
{
// background plane supports touch events
background = [CC3PlaneNode nodeWithName: BACKGROUND_PROJECTION_PLANE_NAME];
[background populateAsCenteredRectangleWithSize: CGSizeMake(10.0, 10.0)
withTexture: [CC3Texture textureFromFile: #"transparent1x1.png"]
invertTexture: YES];
[background setIsOpaque: NO];
[background retainVertexLocations];
[background setLocation: cc3v(0, 0, 0.001)];
[self addChild: background];
}
// ...
- (void) moveNode: (CC3Node*) node toScreenLocation: (CGPoint) point
{
// update node on screen
CC3Plane groundPlane = self.background.plane;
CC3Vector4 touchLoc = [self.activeCamera unprojectPoint: point ontoPlane: groundPlane];
CC3Vector newLoc = cc3v(touchLoc.x,touchLoc.y,touchLoc.z);
[node setLocation: newLoc];
}

Related

Positionning particle in node

Using cocos2d, I'm trying to replace a sprite (item in my code) with a particle system. This code is placed in my board class. This one works:
// Draw the particles
CCParticleSystem *particles = [[CCParticleSystem alloc] initWithDictionary:_popParticles];
particles.position = ccpSub(item.position,ccp(160,160));
particles.autoRemoveOnFinish = TRUE;
[self addChild:particles];
This one doesn't:
// Draw the particles
CCParticleSystem *particles = [[CCParticleSystem alloc] initWithDictionary:_popParticles];
particles.position = item.position;
particles.autoRemoveOnFinish = TRUE;
[self addChild:particles];
I tried player with this but without success:
particles.positionType = CCPositionTypeMake(CCPositionUnitUIPoints, CCPositionUnitUIPoints, CCPositionReferenceCornerBottomLeft);
My board is a 320x320 points CCSprite with anchor point set at 0.5, 0.5
When I log my item.position value, I get something relative to the bottom left corner of my board (from 30,30 to 290,290)
Is using ccpSub the correct way ?
When you destroy a node you also destroy all of it's children nodes, you said you add your particle to 'item' then you destroy that 'item', which means you have no particle anymore.

CCSprite anchorPoint not working as expected?

Let me start by explaining what I am trying to do. I have a full screen animation with about 73 frames and with these images being so large I am not able to use sprite sheets so I am just adding them to an animation as seperate spriteframes. My goal is to have the animation play through and then have it disappear from left to right. The way that I am achieving this look is by updating the width of the (textureRect) of the frames and eventually making the textureRect width 0. So I have set up the CCSprite that I am going to run the animation on.
-(id) init {
if( (self=[super init])) {
self.transSprite = [CCSprite spriteWithFile:#"transition0.pvr.ccz"];
if (CC_CONTENT_SCALE_FACTOR() == 1) {
//iPhone 3Gs
self.transSprite.scaleX = .563;
self.transSprite.scaleY = .665;
self.transSprite.position = ccp(self.transSprite.contentSize.height - 3, -1);
self.transSprite.anchorPoint = ccp(1, 0);
[self addChild:self.transSprite z:5];
}
else if (kiPhone5) {
//iPhone 5
self.transSprite.scale = self.transSprite.scale * 1.335f;
self.transSprite.position = ccp(569, -1);
self.transSprite.anchorPoint = ccp(1, 0);
[self addChild:self.transSprite z:5];
}
else {
//iPhone 4
self.transSprite.scaleX = 1.126;
self.transSprite.scaleY = 1.33;
self.transSprite.position = ccp(481, -1);
self.transSprite.anchorPoint = ccp(1, 0);
[self addChild:self.transSprite z:5];
}
}
return self;
}
So the reason for checking what device is running, is because I did not make 2 versions of the animation frames HD and SD. Instead I just made them a good in between size and then I check to see what device is running and scale the sprite accordingly. So here is my problem I am setting the Sprites anchorPoint to the bottom right hand corner of the screen so that when I change the width of the textureRect it will decrease in size from left to right. Everything seems to be working great with this idea except for when I change the width of the textureRect of each sprite frame.
- (void) rectUpdate3Gs {
for (CCAnimationFrame *frame in transition.frames) {
frame.spriteFrame.rect = CGRectMake(0, 0, 856, 484);
}
}
- (void) retinaRectUpdate {
for (CCAnimationFrame *frame in transition.frames) {
frame.spriteFrame. rect = CGRectMake(0, 0, 428, 242);
}
}
So when I run the animation and start to change the width of the textureRect it decreases from both the left and the right side, it is like the anchorPoint is being ignored. Do the spriteFrames have there own anchorPoint or what is happening.
Here is an illustration of what is happening.This is the CCSprite set up for the full texture and with the anchorPoint in the bottom right corner.
self.transSprite.scaleX = .563;
self.transSprite.scaleY = .665;
self.transSprite.position = ccp(self.transSprite.contentSize.height - 3, -1);
[self addChild:self.transSprite z:5];
[self.transSprite setTextureRect:CGRectMake(0, 0, 856, 484)];
self.transSprite.anchorPoint = ccp(1, 0);
Now this is setting the textureRect of the CCSprite a little smaller.
This is the way that I want it to work, is to subtract the width of the texture from the left to right. But when I change the width of the animation frames to match this subtracted width this is what I get.
I am at a loss as to why this is happening. Do the animation frames not respect the anchor point of the CCSprite they are running on?
Scaling issue aside, there's 2 things you can do. First, and probably easiest, is to simply add a CCLayerColor on top of the animation and scale that down accordingly. This way you don't need to modify every animation frame's rect.
Second option would be to use a clipping node, found here:
Here

cocos2d: Why can't I change a scaled node's position?

I think I'm just understanding scaling/positioning nodes/layers incorrectly. I'm setting up my node like this (node class is derived from CCNode):
-(id) init
{
if ((self = [super init]))
{
// Create parallax background node.
background = [BackgroundNode node];
[self addChild:background z:0];
// Create foreground node.
foreground = [ForegroundLayer node];
[self addChild:foreground z:0];
self.position.y = 500.0f;
self.scaleX = 1.5f;
self.scaleY = 1.5f;
}
return self;
}
It doesn't seem to matter what I set the self.position.y to - the scaled node is always displayed as though it was positioned in the bottom-left of the screen. I've tried playing around with anchorPoint as well, but it doesn't really seem to change anything.
The reason I'm asking is because I'd like to be able to pan vertically when I'm zoomed in - this doesn't seem to really be the right way to accomplish it, though. Any ideas?
self.position.y = 500.0f;
doesn't work. It should be
self.position = ccp(self.position.x, 500.0f);
Please refer to "Cocoa Objective-c Property C structure assign fails".

Is object remain fixed when scrolling background in cocos2d

I have one question when infinite background scrolling is done, is the object remain fixed(like doodle in doodle jump, papy in papi jump) or these object really moves.Is only background move or both (background and object )move.plz someone help me.I am searching for this solution for 4/5 days,but can't get the solution.So plz someone help me. And if object does not move how to create such a illusion of object moving.
If you add the object to the same layer as the scrolling background, then it will scroll as the background scrolls.
If your looking for an effect like the hero in doodle jump, you may want to look at having two or more layers in a scene.
Layer 1: Scrolling Background Layer
Layer 2: Sprite layer
SomeScene.m
CCLayer *backgroundLayer = [[CCLayer alloc] init];
CCLayer *spriteLayer= [[CCLayer alloc] init];
[self addChild:backgroundLayer z:0];
[self addChild:spriteLayer z:1];
//Hero stays in one spot regardless of background scrolling.
CCSprite *squidHero = [[CCSprite alloc] initWithFile:#"squid.png"];
[spriteLayer addChild:squidHero];
If you want objects to scroll with the background add it to the background layer:
//Platform moves with background.
CCSprite *bouncePlatform= [[CCSprite alloc] initWithFile:#"bouncePlatform.png"];
[backgroundLayer addChild:bouncePlatform];
Another alternative is to use a CCFollow action. You would code as if the background is static (which it will be) and the player is moving (which it will be), but add a CCFollow action to the player. This essentially moves the camera so that it tracks your player.
You can also modify the classes so that you can get the CCFollow action to follow with an offset (i.e., so the player is not in the middle of the screen) as well as to have a smoothing effect to it, so that when the player moves, the follow action is not jerky. See the below code:
*NOTE I am using cocos2d-x, the c++ port. The methods are similar in cocos2d, and you should be able to modify these to fit the cocos2d syntax. Or search around -- I found these for cocos2d and then ported to c++.
//defines the action to constantly follow the player (in my case, "runner.p_sprite is the sprite pointing to the player)
FollowWithOffset* followAction = FollowWithOffset::create(runner.p_sprite, CCRectZero);
runAction(followAction);
And separately, I have copied the class definition for CCFollow to create my own class, CCFollowWithAction. This also has a smoothing effect (you can look this up more online) so that when the player moves, the actions are not jerky. I modified "initWithTarget," to take into account an offset, and "step," to add a smoothing action. You can see the modifications in the comments below.
bool FollowWithOffset::initWithTarget(CCNode *pFollowedNode, const CCRect& rect/* = CCRectZero*/)
{
CCAssert(pFollowedNode != NULL, "");
pFollowedNode->retain();
m_pobFollowedNode = pFollowedNode;
if (rect.equals(CCRectZero))
{
m_bBoundarySet = false;
}
else
{
m_bBoundarySet = true;
}
m_bBoundaryFullyCovered = false;
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
m_obFullScreenSize = CCPointMake(winSize.width, winSize.height);
//m_obHalfScreenSize = ccpMult(m_obFullScreenSize, 0.5f);
m_obHalfScreenSize = CCPointMake(m_obFullScreenSize.x/2 + RUNNER_FOLLOW_OFFSET_X,
m_obFullScreenSize.y/2 + RUNNER_FOLLOW_OFFSET_Y);
if (m_bBoundarySet)
{
m_fLeftBoundary = -((rect.origin.x+rect.size.width) - m_obFullScreenSize.x);
m_fRightBoundary = -rect.origin.x ;
m_fTopBoundary = -rect.origin.y;
m_fBottomBoundary = -((rect.origin.y+rect.size.height) - m_obFullScreenSize.y);
if(m_fRightBoundary < m_fLeftBoundary)
{
// screen width is larger than world's boundary width
//set both in the middle of the world
m_fRightBoundary = m_fLeftBoundary = (m_fLeftBoundary + m_fRightBoundary) / 2;
}
if(m_fTopBoundary < m_fBottomBoundary)
{
// screen width is larger than world's boundary width
//set both in the middle of the world
m_fTopBoundary = m_fBottomBoundary = (m_fTopBoundary + m_fBottomBoundary) / 2;
}
if( (m_fTopBoundary == m_fBottomBoundary) && (m_fLeftBoundary == m_fRightBoundary) )
{
m_bBoundaryFullyCovered = true;
}
}
return true;
}
void FollowWithOffset::step(float dt)
{
CC_UNUSED_PARAM(dt);
if(m_bBoundarySet){
// whole map fits inside a single screen, no need to modify the position - unless map boundaries are increased
if(m_bBoundaryFullyCovered)
return;
CCPoint tempPos = ccpSub( m_obHalfScreenSize, m_pobFollowedNode->getPosition());
m_pTarget->setPosition(ccp(clampf(tempPos.x, m_fLeftBoundary, m_fRightBoundary),
clampf(tempPos.y, m_fBottomBoundary, m_fTopBoundary)));
}
else{
//custom written code to add in support for a smooth ccfollow action
CCPoint tempPos = ccpSub( m_obHalfScreenSize, m_pobFollowedNode->getPosition());
CCPoint moveVect = ccpMult(ccpSub(tempPos,m_pTarget->getPosition()),0.25); //0.25 is the smooth constant.
CCPoint newPos = ccpAdd(m_pTarget->getPosition(), moveVect);
m_pTarget->setPosition(newPos);
}
}

Cocos2d iPhone - Sprite cliping/mask/frame

how can i clip/crop/mask or just set the frame of a CCSprite in Cocos2D?
Something similar to:
setting the frame for UIView, with clipping subviews = TRUE
My CCSprite Main Sprite have multiple Child Sprite added to it.
I only want Mask part of that Main Sprite Sprite visible.
Is there a way to clip or use a mask for CCSprite?
I could cut the background and layer that on top, leaving only that visible area, but is that the only way?!
here's a sample image demonstrating what I'm trying to achieve:
(source: dnamique.com)
I ended up using GL_SCISSOR.
in MainSprite I impemented:
- (void) visit
{
if (!self.visible) {
return;
}
glEnable(GL_SCISSOR_TEST);
glScissor(x, y, width, height);
[super visit];
glDisable(GL_SCISSOR_TEST);
}
This will clip or mask the specified area.
The only tricky bit is that in Landscape mode Cocos2D has 0,0 at the bottom-left side of the screen, while OpenGL has it at the bottom-right corner as it doesn't consider the orientation of the screen.
In other words, for OpenGL consider you have a rotated portrait Screen.
I wrote a ClippingNode class which does exactly that. You can add other nodes (sprites, labels, etc.) to the ClippingNode and they will only be drawn in the region specified by the ClippingNode. It also takes device rotation into account.
Internally it uses GL_SCISSOR_TEST like in Bach's answer.
http://www.learn-cocos2d.com/2011/01/cocos2d-gem-clippingnode/
I tried using Steffen Itterheim's ClippingNode, but was unable to get to work in a sufficiently robust
enough fashion for my needs.
Believe it or not, the below code works fairly well and should be code complete. It handles device orientation changes, anchorPoint, position, scale (scaleX, scaleY). For cocos2d v2, you may just need to
comment out the glPushMatrix and glPopMatrix calls..
To use, simply set the position and contentSize properties and add the child/children you want clipped to this ClippingNode instance. The contentSize property is used to define the dimensions of the clipping region.
example of usage:
ClippingNode *clipNode = [[ClippingNode alloc] init];
clipNode.anchorPoint = ccp(0.5f, 0);
clipNode.position = ccp(100, 25);
clipNode.contentSize = CGSizeMake(120, 120);
// add clipNode to your node hierarchy.
[parentNode addChild:clipNode];
// add one or more children to your clipNode:
[clipNode addChild:child1];
// ClippingNode.h
// CC0 - (public domain. Use in anyway you see fit.)
// No warranty of any kind is expressed or implied.
//
// by UChin Kim.
//
// the caller can simply set the regular cocos2d
// properties: position and contentSize to define the clipping region implicitly (i.e. the
// position and contentSize of the ClippingNode is the clipping region to be used).
// as an added bonus, position seems to work as expected (relative to parent node, instead of
// requiring absolute positioning).
//
// also, anchorPoint and scale properties seem to work as expected as well..
// no special code is neeed to handle device orientation changes correctly..
//
// To visually see exactly what is being clipped, set the following #define
// #define SHOW_CLIPPED_REGION_IN_LIGHT_RED 1
//
#import "cocos2d.h"
#interface ClippingNode : CCNode
#end
//
// ClippingNode.m
//
#import "ClippingNode.h"
#implementation ClippingNode
-(void) visit
{
CGPoint worldOrg = [self convertToWorldSpace:ccp(0, 0)];
CGPoint dest = [self convertToWorldSpace:ccp(self.contentSize.width, self.contentSize.height)];
CGPoint dims = ccpSub(dest, worldOrg);
glPushMatrix();
glEnable(GL_SCISSOR_TEST);
glScissor(worldOrg.x, worldOrg.y, dims.x, dims.y);
#if SHOW_CLIPPED_REGION_IN_LIGHT_RED
glColor4ub(64, 0, 0, 128);
ccDrawSolidRect(ccp(0, 0), ccp(1024, 1024));
#endif
[super visit];
glDisable(GL_SCISSOR_TEST);
glPopMatrix();
}
#end