How to get collision between bat of player and ball and ignore player's body - cocos2d-x

I have baseball player animation where player are hitting with bat, I have 90 frames in that animation and on sprite for ball. I added circle physic body to ball. How to make, what is a concept, to get collision only with ball and bat and not between player's body and ball ?
Bat is on every image together with player.
I am using Cocos2d-x and Chipmunk but I can switch to Box2d easily if this problem is solvable.

What you are looking for is a way to distinguish between collisions in your physics world. When using box2D you can set the user data for the physics body. When a collision happens you can get the two bodies that are colliding and get the user information set on it. Then handle your collision appropriately.
Pseudo-code below to create a body:
b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(tileNode->getPositionX() / Pixel_To_Meter_Ratio,
tileNode->getPositionY()/ Pixel_To_Meter_Ratio);
auto b2CircleShape ballShape;
ballShape->m_radius = ballSize / PTM_RATIO; // Pixel to meter ration is 32.0 in my project
auto ballBody= physicsWorld->CreateBody(ballBodyDef);
// This will be used later on when you want to have different reactions for different collisions.
ballBody->SetUserData("BallBody");
Using similar code above create your bat body (will not put all the code below).
...
auto batBody = physicsWorld->CreateBody(batBodyDef);
batBody->setUserData("BatBody");
When doing your check in your contact listener you can ignore all collisions that has user data that does not match BallBody and BatBody. Something like below in your collision handler.
auto objectOne = contact->GetFixtureA()->GetBody();
auto objectTwo = contact->GetFixtureB()->GetBody();
auto objectOneUserData = (objectOne->GetUserData());
auto objectTwoUserData = (objectTwo->GetUserData());
Do your checks on the userData above and return out of the function. This should do the trick. It's what I use to handle or ignore specific types of collisions.
I hope this helps.

Related

Trigger a function when specific frame number is reached - AS3

I wanted friends, do the following when my MC get a determanido internal quandro, it triggers a function to another MC. for example when the ball hit the wall, a person goes to search - la, I have tried using :
("root") {root.MC.play ()}
Translation from comments:
Friends, I have an MC_1 with 10 frames, when it reaches frame 5, I want another movieClip MC_2 to respond (eg: to move or fade etc)
creating a ENTER_FRAME listener for your MC_1 is the easiest way to achieve this
MC_1.addEventListener(Event.ENTER_FRAME,respond);
function respond(e:Event):void{
if(MC_1.currentFrame>=5)
MC_2.gotoAndPlay(2);
//or any other respose you want from MC_2
}
addFrameScript can be used in AS3 to specify a function to execute on reaching a MovieClip frame.
MovieClip.addFrameScript(index:int, func:Function);
A sample implementation of this:
// addFrameScript's index is zero Based, hence 4 means frame 5
MC_1.addFrameScript(4, funcToExecute);
function funcToExecute():void{
// this will get called when MC_1 reaches frame 5
// do stuff here, like manipulating MC_2, etc...
}

AS3. How to change character's template in adobe flash cs5 using AS3?

I'm creating flash game. Here will be abillity to choose one of two (or more) character's. So I have in library created symbol hero. It have 7 animations on click (moving, jumping, attacking etc..)
So I want to create something like hero 2, that player could choose which one likes more. Just how to do that? Create new layer in hero and add animations or how?
I'm asking that because in Action Script 3 I'm adding hero in this case and It always will add the same:
private function create_hero()
{
addChild(Hero);
Hero.gotoAndStop("stay");
Hero.x = stage.stageWidth/2;;
Hero.y = ground.y - 60;
Hero.x_speed = 0;
Hero.y_speed = 0;
}
Maybe here is abillity to make something like that layer2.addChild(Hero);?
Or I need to create new symbol hero2? I don't like this idea, because I have long code to control hero, so for every character I'll need to dublicate code. Could you help me? Thank you.
The proper way is to dynamically create an instance Hero at game start based on the game player's selection. You indeed create two (or more) symbols in Flash CS, with common frame labeling (you can use different animation lengths for different heroes), then, once you've got your hero selection (hero1,hero2,hero3 etc, regardless of their amount) you get the class name from selection and get your Hero variable to be assigned an instance of the respective class. An example:
static var heroes:Array=[hero1,hero2,hero3]; // note: symbol names!
var Hero:MovieClip; // note, not "hero1" or anything, but general MovieClip type
public function selectHero(what:int):void {
// this is called with correct "what", design yourself. I use array index
var whatHero:Class = heroes[what]; // get selected hero symbol
if (Hero && Hero.parent) Hero.parent.removeChild(Hero);
// clean up previous hero. Drop listeners here, if any
Hero = new whatHero(); // get new hero
// process as usual, don't forget to "addChild(Hero)" somewhere
}
How this works: First, you give the player a hero selection dialogue, and call selectHero with proper value of what (0 for hero1, 1 for hero2, etc, as you make your heroes array). Then, the whatHero variable is assigned the corresponding class (yes, one can assign classes to variables in AS3!) And then the class gets instantiated via new construction, and the resultant movie clip is then assigned to Hero variable. After this is done, you can use your hero as before.

How do I HitTest two rotating objects properly? (A way to avoid bounding boxes)

I took an intro level flash course in college this semester and our final task was to make a mini-flash game.
I had to make a pipe-dream type game where there are a number of levels, and in each level you have to align the pipes so that the water flows and then you can pass to the next level.
I successfully made the first level, but upon making the second level,
where I placed a lot of curved pipes (by curved pipes I mean the attached image: ![Curved Pipe]: (http://imgur.com/mwpXAMn) )
I discovered that the method I use to decide when a level is complete is not working properly.
I was using HitTestObject, basically, I was testing whether 2 objects, Pipe_1, and Pipe_2, were intersecting. If all pipes intersected in the correct way, then procession to the next level is granted.
The problem with this I discovered is that flash has bounding boxes for movie clips you make, and that HitestObject uses bounding boxes to test for hits. Therefore, when you rotate a leftpipe so that it does not touch a straight pipe on screen, the bounding boxes still touch and it returns "collision" when in fact it is not actually touching on screen.
I looked up and found that you can use HitTestPoint but I can't figure out how to somehow make dynamic variables (that change upon rotation of object) that store one or two specific points on the leftpipe, say the two ends of it.
Once If I figure out how to get these values into a variable correctly, then I can figure out how to do HitTestpoint.
Also, I know of the LocaltoGlobal function but no matter what I try it keeps coming up with:
"Scene 1, Layer 'Layer 1', Frame 1, Line 30 1118: Implicit coercion of a value with static type Object to a possibly unrelated type flash.geom:Point."
meaning I don't know the correct code to store an x and a y coordinate as dynamic variables.
edit: ok since a person asked, I hunted this piece of code off the web and this is the one I was trying to play around with but to no avail:
How to use HitTest for 2 rectangles, r1 is rectangle 1 r2 is rectangle 2.
var r1width:Number = 135.0; //width of retangle 1 whith rotation 0
var r2width:Number = 93.0; //width of retangle 2 whith rotation 0
var p1:Object = {x:(r1width/2), y:(r1width/2)};
var p2:Object = {x:(-r1width/2), y:(r1width/2)};
var p3:Object = {x:(-r1width/2), y:(-r1width/2)};
var p4:Object = {x:(r1width/2), y:(-r1width/2)};
r1.localToGlobal(p1);
r1.localToGlobal(p2);
r1.localToGlobal(p3);
r1.localToGlobal(p4);
var p5:Object = {x:(r2width/2), y:(r2width/2)};
var p6:Object = {x:(-r2width/2), y:(r2width/2)};
var p7:Object = {x:(-r2width/2), y:(-r2width/2)};
var p8:Object = {x:(r2width/2), y:(-r2width/2)};
r2.localToGlobal(p5);
r2.localToGlobal(p6);
r2.localToGlobal(p7);
r2.localToGlobal(p8);
if((r2.hitTest(p1.x, p1.y, true))||(r2.hitTest(p2.x, p2.y, true))||(r2.hitTest(p3.x,
p3.y, true))||(r2.hitTest(p4.x, p4.y, true)))
{
trace('collision');
}
if((r1.hitTest(p5.x, p5.y, true))||(r1.hitTest(p6.x, p6.y, true))||(r1.hitTest(p7.x,
p7.y, true))||(r1.hitTest(p8.x, p8.y, true)))
{
trace('collision');
}
I did not write this code and it does not work. I'm not sure what "Object" is because I've never used it before, I'm assuming in this case it's sort of acting like a coordinate pair.
Also, this code is to hittest 2 rectangles, whereas I'm using an L-shaped pipe, so the x/y calculation would be quite different I imagine.
This code above gives the same error that I posted before:
Implicit coercion of a value with static type Object to a possibly unrelated type flash.geom:Point.
and it gives it first on line r1.localToGlobal(p1);
Instead of using Object, you need to use Point like so:
var p1:Point = new Point(r1width/2, r1width/2);

How to do slow motion effect in flash game with box2d

As i am working on top view racing game in which am trying to add slow motion effect when a car hits objects. I have tried with decreasing Stage.frameRate but the game appears lagging. and i have also tried with online tutorial called touch my pixel ( ref : http://blog.touchmypixel.com/2009/12/box2d-contactpoint-filtering/ ). But i didn't understand.
Is there any solution for showing such kind of slow motion effect. can anybody help me in this regard
Thanks and regards,
Chandrasekhar
Easiest way would be to have a global modifier property somewhere which can be used to multiply the movement of everything in the game.
For example, you could have the property speedModifier default to 1.
public var speedModifier:Number = 1;
And whenever you apply velocities, just multiply by the modifier:
body.SetLinearVelocity( new b2Vec2(x * speedModifier, y * speedModifier) );
This way all you need to do to half the speed of the game is to half the modifier:
speedModifier = 0.5;
To keep your code tidier and make managing this component of your game easier, there is probably a straightforward way to iterate over all of the bodies within the Box2D world and modify their velocities at the top of each update step. Something along the lines of:
for each(var i:b2Body in world.GetBodyList())
{
var currentVel:b2Vec2 = i.GetLinearVelocity();
var newVel:b2Vec2 = new b2Vec2(
currentVel.x * speedModifier,
currentVel.y * speedModifier
);
i.SetLinearVelocity( newVel );
}

Walkcycles and timing in pygame

I have a pygame.Timer running in my game calling a draw function 32 times/second. The drawing method gets positions from all elements on my screen and blits them accordingly. However, I want the main character to walk around slower than other objects move.
Should I set up a timer specifically for it or should I just blit the same frames several times? Is there any better way to do it? A push in the right direction would be awesome :)
(If anyone's interested, here is the code that currently controls what frames to send to the drawing: http://github.com/kallepersson/subterranean-ng/blob/master/Player.py#L88)
Your walk cycle frame (like all motion) should be a function of absolute time, not of frame count. e.g.:
def walk_frame(millis, frames_per_second, framecount, start_millis=0):
millis_per_frame = 1000 / frames_per_second
elapsed_millis = millis - start_millis
total_frames = elapsed_millis / millis_per_frame
return total_frames % framecount