I've got a subclass of CCSprite that knows how to move itself based on two float properties, velX and velY. I call the subclass's - (void)update:(ccTime)dt method from the method of the same name in my game layer.
I use dt to scale how much I move the player and it works great. I'd like to use dt to scale a deceleration factor to make how the player slows down consistent regardless of how often it's updated.
But it just makes my CCSprite not even show up.
Here's the CCSprite class...
#import "Player.h"
#define kDeceleration 0.95
#implementation Player
#synthesize velX, velY;
# pragma mark
+ (id)player
{
Player *player = nil;
if ((player = [[[super alloc] initWithFile:#"rocket.png"] autorelease])) {
player.velX = 0.0;
player.velY = 0.0;
}
return player;
}
- (void)update:(ccTime)dt
{
CGSize winSize = [[CCDirector sharedDirector] winSize];
// move
self.position = ccp(self.position.x + self.velX * dt, self.position.y + self.velY * dt);
if (self.position.x < -self.contentSize.width/2) self.position = ccp(winSize.width + self.contentSize.width/2, self.position.y);
if (self.position.x > winSize.width + self.contentSize.width/2) self.position = ccp(-self.contentSize.width/2, self.position.y);
if (self.position.y < -self.contentSize.width/2) self.position = ccp(self.position.x, winSize.height + self.contentSize.width/2);
if (self.position.y > winSize.height + self.contentSize.width/2) self.position = ccp(self.position.x, -self.contentSize.width/2);
// decelerate
self.velX *= kDeceleration * 0.0165 / dt; // works if the line is: self.velX *= kDeceleration;
if (fabs(self.velX) < 1.0) self.velX = 0.0;
self.velY *= kDeceleration * 0.0165 / dt; // works if the line is: self.velY *= kDeceleration;
if (fabs(self.velY) < 1.0) self.velY = 0.0;
}
- (void)draw
{
[super draw];
glLineWidth(1);
ccDrawCircle(ccp(self.contentSize.width/2, self.contentSize.height/2), 3*self.contentSize.width/4, CC_DEGREES_TO_RADIANS(360), 60, NO);
}
#end
The problem is in the // decelerate section. If I leave out the * 0.0165 / dt part of the two lines that decelerate the player, it works, but it's way faster on the phone than the simulator due to framerate differences. This should scale it, but it just screws it up.
I've tried all kinds of NSLogging and if I use dt at all, I get nan for the value of my velX and velY properties.
Could it have something to do with using the method name -update?
Try using this formula instead:
float decelerator = pow(kDeceleration, 60 * dt);
self.velX *= decelerator;
self.velY *= decelerator;
The logic behind the math:
Suppose the framerate on simulator is at 30fps compared to the normal 60fps on device. Thus, for every frame on simulator, the device already shows 2 frames. Thus every call on the update on simulator should give the same result for 2 calls on device. After two calls on device, self.velX has been multiplied by kDeceleration two times, meaning the new value is equal to self.velX * kDeceleration * kDeceleration. By same logic, if the framerate on simulator is 1/3 of that on device, the new value is self.velX * kDeceleration * kDeceleration * kDeceleration. Thus, we can generalize it as self.velX * pow(kDeceleration, n) where n is the number of times the update method to be called to catch up with framerate of 60fps, which is 60 * dt.
Related
I'm using accelerometer in my first Cocos2D game and it work fine, i'm able to move the sprite using the below code however, when i change the orientation from landscapeLeft to landscapeRight, the sprite stops responding to Y coordination, and the sprite goes to the top of the screen and doesn't properly respond... I believe it's because of changing the device orientation, but i'm not sure since i'm pretty new to App Development, any help will be appreciated.
Here is the sample code i'm using...
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
//this determines how sensitive the accelerometer reacts (higher = more sensitive)
NSUserDefaults *defaulObj = [NSUserDefaults standardUserDefaults];
float sensitivity = [defaulObj floatForKey:#"Sensitivity"]; //10.0f
if (!sensitivity) {
sensitivity = 6;
}
// this controls how quickly the velocity decelerates (lower = quicker to change direction)
float deceleration = 0.4f;
static float xVal = 0;
if (!self.isFlag) {
xVal = -acceleration.x;
self.isFlag = TRUE;
}
playerVelocity.x = playerVelocity.x * deceleration + (xVal + acceleration.x) * sensitivity;
playerVelocity.y = playerVelocity.y * deceleration + acceleration.y * sensitivity;
playerVelocity.y = playerVelocity.y*-1;
}
Perhaps this helps out, flips Y along your current device orientation.
float rotatedY = acceleration.y;
if ([UIApplication sharedApplication].statusBarOrientation==UIInterfaceOrientationLandscapeLeft) {
rotatedY *= -1;
}
then use rotatedY insteat of acceleration.y
I am making an iphone app where a ball will roll around the screen based on how the user tilts the device. If the device is lies flat on the table theoretically the ball would not move. If the device is tilted standing completely upward the I want the ball to roll straight down at maximum speed. The speed depends on how far from the flat position the device is tilted. Also, it also works for if the user tilts right or left or up or combinations of the four. I am using the accelerometer right now and the ball moves and it works okay, I am just not real familiar with physics. If someone has any suggestions on how to get this to work smoothly please let me know.
Thanks!
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
float xx = -[acceleration x];
float yy = [acceleration y];
float z = -[acceleration z];
z = 1 - z;
NSString * zaxis = [NSString stringWithFormat:#"%f", z];
lblz.text = zaxis;
lbly.text = [NSString stringWithFormat:#"%f", yy];
lblx.text = [NSString stringWithFormat:#"%f", xx];
CGFloat newx;
CGFloat newy;
if (yy > 0)
{
newy = ball.center.y - ((1 - yy) * z);
}
else
{
newy = ball.center.y + ((1 - yy) * z);
}
if (xx > 0)
{
newx = ball.center.x - ((1 - xx) * z);
}
else
{
newx = ball.center.x + ((1 - xx) * z);
}
CGPoint newPoint = CGPointMake(newx, newy);
ball.center = newPoint;
If you want to make it look more realistic and leverage existing stuff, look at some of the existing physics engines and 2d frameworks, Box2d and Cocos2d, but there are many others.
I think the key thing you are messing here is the difference between acceleration and velocity. You want the 'amount of tilt' to work as an acceleration. Each frame the balls Velocity should change by the acceleration, then the balls position should change by the balls velocity.
So just in X it should be something like:
float accelX = acceleration.x;
mVel.x += accelX; \\mVel is a member variable you have to store
ball.center.x += mVel.x;
---More Complex version
Now the more I think about it, it might not be the 'amount of tilt' you want to be the acceleration. You might want the amount of tilt to be the 'Target Velocity.' But you still want to use an acceleration to get there.
mTargetVel.x = acceleration.x;
//Now apply an acceleration to the velocity to move towards the Target Velocity
if(mVel.x < mTargetVel.x) {
mVel.x += ACCEL_X; //ACCEL_X is just a constant value that works well for you
}
else if(mVel.x > mTargetVel.x) {
mVel.x -= ACCEL_X;
}
//Now update the position based on the new velocity
ball.center.x += mVel.x;
I am new in Box2D....
I have ball image in CCSprite. I want to move ball in whole screen using accelerometer...
tell me
How to use accelerometer in box2d??
Thanks...in advance
The standard cocos2d-box2d template file moves boxes using the accelerometer by applying gravity relative to the accelerometer value.
- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
static float prevX=0, prevY=0;
//#define kFilterFactor 0.05f
#define kFilterFactor 1.0f // don't use filter. the code is here just as an example
float accelX = (float) acceleration.x * kFilterFactor + (1- kFilterFactor)*prevX;
float accelY = (float) acceleration.y * kFilterFactor + (1- kFilterFactor)*prevY;
prevX = accelX;
prevY = accelY;
// accelerometer values are in "Portrait" mode. Change them to Landscape left
// multiply the gravity by 10
b2Vec2 gravity( -accelY * 10, accelX * 10);
world->SetGravity( gravity );
}
You need to be more specific on what you want the ball to do dependent on how you move the phone. Your question is difficult to answer in its current form.
Get the accelerometer measurements and say Force = coefficient*measurements. The apply this force to your b2Body
Let your Ball Sprite having tag is 1.
Replace this code with your Accelerometer delegate,
I test it on device, its working.
and your ball will move with accelerometer.
-(void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
#define kFilterFactor 0.75
accelerometer.updateInterval = 1.0f/60.0f;
static UIAccelerationValue rollingX = 0, rollingY = 0;
for (b2Body *b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() != NULL)
{
CCSprite *sprite = (CCSprite*)b->GetUserData();
if (sprite.tag == 1) {
rollingX = (acceleration.x * kFilterFactor) + (rollingX * 0.25);
rollingY = (acceleration.y * kFilterFactor) + (rollingY * 0.25);
float accelX = rollingX;
float accelY = rollingY;
CGPoint moveNewPosition = sprite.position;
if (accelX > 0.1) {
moveNewPosition.y += 2;
} if (accelX < 0.1) {
moveNewPosition.y -= 2;
}
if (accelY > 0.1) {
moveNewPosition.x -= 2;
} if (accelY < -0.1) {
moveNewPosition.x += 2;
}
b->SetLinearVelocity(b2Vec2(2,2));
sprite.position = ccp(moveNewPosition.x , moveNewPosition.y );
sprite.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
}
}
I hope it'll work.
I'm trying to rotate a sprite using the accelerometer. when I tilt right, I want him to rotate slightly to the right, and when I tilt left, I want him to rotate slightly to the left...
Thanks in advance,
Reed
Firs off - in your h file you need to make the following variables:
UIAccelerationValue accelerationX;
UIAccelerationValue accelerationY;
float currentRawReading;
float calibrationOffset;
Also ensure that your h file has:
#interface myViewName : UIViewController <UIAccelerometerDelegate>
Then in your .m file just below your imports at the top put:
#define kFilteringFactor 0.05
CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
CGFloat RadiansToDegrees(CGFloat radians) {return radians * 180/M_PI;};
Then in your .m file on your viewDidLoad Function put:
UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = self;
accel.updateInterval = 1.0f/60.0f;
also add the following function to your .m file:
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
accelerationX = acceleration.x * kFilteringFactor + accelerationX * (1.0 - kFilteringFactor);
accelerationY = acceleration.y * kFilteringFactor + accelerationY * (1.0 - kFilteringFactor);
// keep the raw reading, to use during calibrations
currentRawReading = atan2(accelerationY, accelerationX);
float rotation = -RadiansToDegrees(currentRawReading);
targetView.transform = CGAffineTransformMakeRotation(-(DegreesToRadians(rotation)));
//targetView.transform = CGAffineTransformRotate(targetView.transform, -(rotation * 3)); //if you want easing
}
you will have to tweak it slightly based on what view or object you are targeting -- but thats pretty much it.
Hope this helps,
Michael
Shouldn't be too difficult. Just have somewhere in your code that handles the UIAccelerometerDelegate class and apply changes to your sprites based on the values you receive through parameters to the – accelerometer:didAccelerate: callback.
Apple docs for the delegate class are available at...
https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIAccelerometerDelegate_Protocol/UIAccelerometerDelegate/UIAccelerometerDelegate.html
In the delegate function of accelerometer just write the code -->>
float angleRadians = atanf((float)X_Position / (float)Y_Position);
float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);
float cocosAngle = 1 * angleDegrees;
sprite.rotation = cocosAngle;
and the sprite will get rotated to desired angle with changes in the values of X_position, Y_Position and angle.
Njoy.. :)
I am trying to change my Sprite anchor point so that I can rotate over a 0.0f,0.0f anchorpoint. At first my object is rotation at the default anchor point (0.5f,0.5f). However later on I need it to rotate over a 0.0,0.0 AnchorPoint.
The problem is I cannot change the anchor point and change the position accordingly, so it stays on the same position, without the object appearing to quickly move and reposition to its original point.
Is there a way I can set the anchor point and the position of my Sprite at once, without it moving at all?. Thank you.
-Oscar
I found a solution to this with a UIView elsewhere, and rewrote it for cocos2d:
- (void)setAnchorPoint:(CGPoint)anchorPoint forSprite:(CCSprite *)sprite
{
CGPoint newPoint = CGPointMake(sprite.contentSize.width * anchorPoint.x, sprite.contentSize.height * anchorPoint.y);
CGPoint oldPoint = CGPointMake(sprite.contentSize.width * sprite.anchorPoint.x, sprite.contentSize.height * sprite.anchorPoint.y);
newPoint = CGPointApplyAffineTransform(newPoint, [sprite nodeToWorldTransform]);
oldPoint = CGPointApplyAffineTransform(oldPoint, [sprite nodeToWorldTransform]);
CGPoint position = sprite.position;
position.x -= oldPoint.x;
position.x += newPoint.x;
position.y -= oldPoint.y;
position.y += newPoint.y;
sprite.position = position;
sprite.anchorPoint = anchorPoint;
}
This is a good question, and I don't know the full answer yet.
As you may have noticed, the anchorPoint cannot be changed without affecting scale and rotation.
For scaled sprites:
You have to simultaneously change the anchorPoint and position of your sprite. See this question for a hint
For rotated sprites:
Intuition says you would need to simultaneously change anchorPoint, rotation, and position. (I have no idea how to compute this.)
NOTE: I'm still learning graphics programming, so I'm not 100% able to compute this stuff yet.
I've needed this a couple of times and decided to make a extension for CCNode, tested it abit and seems to work fine. Can be really useful to some :)
It's tested with 1.x but It should work fine in 2.x too. Supports transformed nodes and HD.
Just add this to your project and import whenever you need it - It will be added to all classes deriving from CCNode. (CCSprite, CCLayer)
Interface
#import "cocos2d.h"
#interface CCNode (Extensions)
// Returns the parent coordinate for an anchorpoint. Useful for aligning nodes with different anchorpoints for instance
-(CGPoint)positionOfAnchorPoint:(CGPoint)anchor;
// As above but using anchorpoint in points rather than percentage
-(CGPoint)positionOfAnchorPointInPoints:(CGPoint)anchor;
//Sets the anchorpoint, to not move the node set lockPosition to `YES`. Setting it to `NO` is equal to setAnchorPoint, I thought this would be good for readability so you always know what you do when you move the anchorpoint
-(void)setAnchorPoint:(CGPoint)a lockPosition:(BOOL)lockPosition;
#end
Implementation
#import "CCNode+AnchorPos.h"
#implementation CCNode (Extensions)
-(CGPoint)positionOfAnchorPoint:(CGPoint)anchor
{
float x = anchor.x * self.contentSizeInPixels.width;
float y = anchor.y * self.contentSizeInPixels.height;
CGPoint pos = ccp(x,y);
pos = CGPointApplyAffineTransform(pos, [self nodeToParentTransform]);
return ccpMult(pos, 1/CC_CONTENT_SCALE_FACTOR());
}
-(CGPoint)positionOfAnchorPointInPoints:(CGPoint)anchor;
{
CGPoint anchorPointInPercent = ccp(anchor.x/self.contentSize.width, anchor.y/self.contentSize.height);
return [self positionOfAnchorPoint:anchorPointInPercent];
}
-(void)setAnchorPoint:(CGPoint)a lockPosition:(BOOL)lockPosition
{
CGPoint tempPos = [self positionOfAnchorPoint:a];
self.anchorPoint = a;
if(lockPosition)
{
self.position = tempPos;
}
}
#end
Cocos2d-x + Fixed scale
YourClass.h
virtual cocos2d::Vec2 positionFromSprite(cocos2d::Vec2 newAnchorPoint, cocos2d::Sprite *sprite);
YourClass.m
Vec2 YourClass::positionFromSprite(Vec2 newAnchorPoint, cocos2d::Sprite *sprite) {
Rect rect = sprite->getSpriteFrame()->getRect();
Vec2 oldAnchorPoint = sprite->getAnchorPoint();
float scaleX = sprite->getScaleX();
float scaleY = sprite->getScaleY();
Vec2 newPoint = Vec2(rect.size.width * newAnchorPoint.x * scaleX, rect.size.height * newAnchorPoint.y * scaleY);
Vec2 oldPoint = Vec2(rect.size.width * oldAnchorPoint.x * scaleX, rect.size.height * oldAnchorPoint.y * scaleY);
Vec2 position = sprite->getPosition();
position.x -= oldPoint.x;
position.x += newPoint.x;
position.y -= oldPoint.y;
position.y += newPoint.y;
return position;
}