how to place a sprite at touch position - cocos2d-x-3.x

I follow the lecture of this website:
website
My code is same as first part of the website.But the position where the label placed in is uppon the place I clicked at.
Could anybody help me?

wrong code is at
bool AppDelegate::applicationDidFinishLaunching() {
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLViewImpl::create("Hello World");
glview->setFrameSize(640, 480);
director->setOpenGLView(glview);
}
auto scene = HelloWorld::createScene();
director->runWithScene(scene);
return true;
}
the code line;
glview->setFrameSize(640, 480);
setFrameSizw width diffrent size of defalut window size;

Related

Simultaneous touches on scene

I am having one problem while working on touches on the screen. I have two modules attached on the screen, on the Left there is a Joystick which has its own touches, and on the right side I have set of Buttons which have its own actions or, touches, both doesn't work together. I have tried to setup touches instead of callbacks on buttons, and tried replacing the buttons with sprites without any luck.
See my requirement below
Any help or, suggestion is highly appreciated.
Thanks.
See my code below what I have tried
I am using SneakyJoystick for the joystick like below
void Game::prepareJoystick(){
Size winSize = Director::getInstance()->getWinSize();
Rect joystickBaseDimensions;
joystickBaseDimensions = Rect(0, 0, 160.0f, 160.0f);
Point joystickBasePosition;
joystickBasePosition = Vec2(winSize.width*0.08, winSize.height*0.15);
SneakyJoystickSkinnedBase *joystickBase = new SneakyJoystickSkinnedBase();
joystickBase->init();
joystickBase->setPosition(joystickBasePosition);
joystickBase->setBackgroundSprite(CCSprite::create("iphone-joystick.png"));
joystickBase->setThumbSprite(CCSprite::create("iphone-joystick_cursor.png"));
SneakyJoystick *aJoystick = new SneakyJoystick();
aJoystick->initWithRect(joystickBaseDimensions);
aJoystick->autorelease();
joystickBase->setJoystick(aJoystick);
joystickBase->setPosition(joystickBasePosition);
leftJoystick = joystickBase->getJoystick();
leftJoystick->retain();
this->addChild(joystickBase);
joystickBase->setScale(GameConfig::controlScale());
}
And for controls on the right hand side I am using cocos2d::ui::Buttons with their callbacks like below
Button *button=Button::create(imageName);
button->setTouchEnabled(true);
button->setPressedActionEnabled(true);
button->addClickEventListener(callback);
button->setPosition(position);
Both are added on the same scene like I shown in the image graphics. Now both doesn't work together. One blocks another, I tried to add touches delegates and try see my code below
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(Game::onTouchesBegan, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
and handling like below
void GameScene::onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event){
for(int i=0;i<touches.size();i++){
Vec2 touchLocation=touches.at(i)->getLocation();
if(btnPunch->getBoundingBox().containsPoint(touchLocation)){
printf("\nshould punch");
punchCallbackAction(this);
}
}
}
None of above method works for me.
Update 2
Just tested the code below returns always 1
void GameScene::onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event){
printf("\nTouches = %d",(int)touches.size());
}
Update 3
Multitouch is enabled for cocos2dx see below
bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor)
{
CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
convertAttrs();
CCEAGLView *eaglview = [CCEAGLView viewWithFrame: r
pixelFormat: (NSString*)_pixelFormat
depthFormat: _depthFormat
preserveBackbuffer: NO
sharegroup: nil
multiSampling: NO
numberOfSamples: 0];
[eaglview setMultipleTouchEnabled:YES];
_screenSize.width = _designResolutionSize.width = [eaglview getWidth];
_screenSize.height = _designResolutionSize.height = [eaglview getHeight];
// _scaleX = _scaleY = [eaglview contentScaleFactor];
_eaglview = eaglview;
return true;
}
Update 3 GLView initialization
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLViewImpl::create("MyGame");
director->setOpenGLView(glview);
}
There is no Multitouch property for above initialization, do I need to do it in different way ?
If testing on iOS, The multipleTouchEnabled property needs to be set to YES before the view can accept multitouch.
In your AppController.mm, look for function didFinishLaunchingWithOptions and add following line
[eaglView setMultipleTouchEnabled: true];

UIImageView will scale instead of rotation if moved , iOS

hy
i want to make a little animation.the rotation works fine if the image is static.
but when i move my image view it will stretch the image. the image can be moved
whit out a problem if it's not rotated.
-(void)play
{
CGRect ship=image.frame;
ship.origin.x=ship.origin.x+move;
ship.origin.y=ship.origin.y+move2;
image.frame=ship;
}
-(void)rotate
{
int degre=180;
float radian=degre*(3.14/180);
image.transform =CGAffineTransformMakeRotation(radian);
}
When using the transform property you are not allowed to change the position by changing the frame, you have to use the center property.
So this should help:
-(void)play
{
image.center=CGPointMake(image.center.x + move, image.center.y + move2);
}

How do you modify this sample code to stop Image Views from stacking?

http://developer.apple.com/library/ios/#samplecode/Touches/Introduction/Intro.html
I'm new to IOS development, and have been playing around with the IOS dev sample code, trying to learn how things work, etc... I came across this sample code (the classic version, not the gesture recognizers ver.) that does everything I'm looking for, except one thing. When the image views are dragged over another image view, they begin stacking up, and you have to double click the image to separate them.
I've spent forever trying to figure out how to make them not stack up. I think I have to store that a piece is getting being moved in an ivar, and stop it from getting the position of the other views... But I'm not sure how to go about doing it. If someone has the time to modify the sample code to not stack pieces, I'd really appreciate it! I'm dying to find out the solution after the forever I spent trying to do it!
I'll try to be a little specific with what I'm trying to do here... I've made 26 of these image views, making them each a letter of the alphabet. I have 13 image views in two rows. A-M & N-Z. Currently, if I drag the A tile down from the top row, moving it down to a "spelling area" I have to cross over the N-Z row. When I do, the "A" tile (image view) picks up any tile it hovers over. So if I drag the A straight down, it's going to pick up the N tile, because it's going to hover right over it, before getting down to the "spelling" area.
Thanks in advance for any help or direction you can give me!
Well you have this function in the sample code
// Checks to see which view, or views, the point is in and then calls a method to perform the closing animation,
// which is to return the piece to its original size, as if it is being put down by the user.
-(void)dispatchTouchEndEvent:(UIView *)theView toPosition:(CGPoint)position
{
// Check to see which view, or views, the point is in and then animate to that position.
if (CGRectContainsPoint([firstPieceView frame], position)) {
[self animateView:firstPieceView toPosition: position];
}
if (CGRectContainsPoint([secondPieceView frame], position)) {
[self animateView:secondPieceView toPosition: position];
}
if (CGRectContainsPoint([thirdPieceView frame], position)) {
[self animateView:thirdPieceView toPosition: position];
}
// If one piece obscures another, display a message so the user can move the pieces apart
if (CGPointEqualToPoint(firstPieceView.center, secondPieceView.center) ||
CGPointEqualToPoint(firstPieceView.center, thirdPieceView.center) ||
CGPointEqualToPoint(secondPieceView.center, thirdPieceView.center)) {
touchInstructionsText.text = #"Double tap the background to move the pieces apart.";
piecesOnTop = YES;
} else {
piecesOnTop = NO;
}
}
wich you can try to modify to
// Checks to see which view, or views, the point is in and then calls a method to perform the closing animation,
// which is to return the piece to its original size, as if it is being put down by the user.
-(void)dispatchTouchEndEvent:(UIView *)theView toPosition:(CGPoint)position
{
// Check to see which view, or views, the point is in and then animate to that position.
if (CGRectContainsPoint([firstPieceView frame], position)) {
[self animateView:firstPieceView toPosition: position];
}
if (CGRectContainsPoint([secondPieceView frame], position)) {
[self animateView:secondPieceView toPosition: position];
}
if (CGRectContainsPoint([thirdPieceView frame], position)) {
[self animateView:thirdPieceView toPosition: position];
}
// If one piece obscures another, display a message so the user can move the pieces apart
if (CGPointEqualToPoint(firstPieceView.center, secondPieceView.center) ||
CGPointEqualToPoint(firstPieceView.center, thirdPieceView.center) ||
CGPointEqualToPoint(secondPieceView.center, thirdPieceView.center)) {
if (firstPieceView.center.x == secondPieceView.center.x)
secondPieceView.center = CGPointMake(firstPieceView.center.x - 50, firstPieceView.center.y - 50);
if (firstPieceView.center.x == thirdPieceView.center.x)
thirdPieceView.center = CGPointMake(firstPieceView.center.x + 50, firstPieceView.center.y + 50);
if (secondPieceView.center.x == thirdPieceView.center.x)
thirdPieceView.center = CGPointMake(secondPieceView.center.x + 50, secondPieceView.center.y + 50);
touchInstructionsText.text = #"";
} else {
piecesOnTop = NO;
}
}
Let me know if it does what you want...

PagingEnabled for multiple pages in UIScrollView

Edit: See the answer below.
I finally give up and come here to ask you for my problem...
I'm using a UIScrollView for a scrolling menus with little icons.
On each page, with paging enabled, there's an icon in the center, and 2 and a half other visible icons on the left and right. I can move from one icon to its neighbour, and that is fine, but the point is that if I do a fast scrolling, it will not move from more than 3 icons, which is the width of the screen.
What I would want is to be able to scroll on more than 3 icons, and that the magnet behaviour is only triggered when it's slowing down.
I've tried to schedule the scroll view to calculate its velocity, and set the pagingEnabled attribute to NO when it's moving fast and YES again when it's slowing down, but as soon as it is set to YES, the view comes back very fast at its original position, as if it was not detecting that I had brought it to a new page. Would anyone know why it does this? And if I have a way to tell the view "ok, now the paging is enabled but look, you're 15 pages later. Just center on the current page, don't come back at the beginning."
Here's my update function (if it can help):
-(void)update:(ccTime)dt
{
float velocity = fabsf((self.previousOffset-self.scrollView.contentOffset.y)/dt);
self.previousOffset = self.scrollView.contentOffset.y;
CCLOG(#"Velocity: %f", velocity);
if(self.scrollView.pagingEnabled)
{
if(velocity > 100)
{
self.scrollView.pagingEnabled = NO;
}
}
else
{
if(velocity < 100)
{
self.scrollView.pagingEnabled = YES;
}
}
}
I finally found a solution, which was pretty obvious, but that I did not see at the beginning, by using setContentOffset on the scrollView.
Here is the new update function:
-(void)update:(ccTime)dt
{
float velocity = 1000;
if(self.previousOffset)
{
velocity = fabsf((self.previousOffset-self.scrollView.contentOffset.y)/dt);
}
self.previousOffset = self.scrollView.contentOffset.y;
if(velocity < 300)
{
CGSize screenSize = [[CCDirector sharedDirector] winSize];
float halfScreen = screenSize.width/2;
CCLayer *panel = (CCLayer *)[self getChildByTag:1];
SQScrollViewMenu *menu = (SQScrollViewMenu *)[panel getChildByTag:1];
SQMissionItem *currentItem = (SQMissionItem *)[menu getChildByTag:currentPage];
float contentOffsetY = [self.scrollView contentOffset].y;
CCLOG(#"Currentpage: %i ; currentoffsetY: %f", currentPage, contentOffsetY);
float distance = contentOffsetY + [currentItem position].x - halfScreen + panel.position.x + menu.position.x + panel.parent.position.x - 60;
CCLOG(#"Which gives a distance of: %f", distance);
[self.scrollView setContentOffset:CGPointMake(0, distance) animated:YES];
self.previousOffset = 0;
[self unschedule:#selector(update:)];
CCLOG(#"Is unscheduled");
}
}
And it is almost working... at least, it is on simulator. But as soon as I try it on my iPhone 4, it does not work anymore. It always go into that update function, but 7 times among 8, it just blocks the scrollView as it is and does not drags it back to the position I give it... but sometimes it does.
Would anyone have an idea? I found similar issues on the net, but none of them could resolve this...

Need to get position of an UIImage animating from top to bottom of screen

I am using animation for an UIImageView. So,that an image is animating from top to bottom of iPhone screen. I gave start and end positions for that imageView for animation. While it is moving, I want to know the current position of that image on the View.
Can any ne help in this regard.
Thank You
You can get position...
-(SLfloat) getYPos
{
SLfloat pos = 0;
CALayer *layer = yourAnimationView.layer.presentationLayer;
if(layer)
pos = layer.frame.origin.y;
return pos;
}