coco2d-x call function with multiple arguments? - android

I'm working on a cocos2d-x project and got stuck. I want to call a function, delay and than call the same function again. I'm using cocos2d-x 2.2.5. and developing for Android.
This is what I got so far:
CCArray *arr = CCArray::create();
arr->addObject(pSprite);
arr->addObject(pGetal);
CCFiniteTimeAction *fun1 = CCCallFuncO::create(this, callfuncO_selector(GameLayer::animateFlip), arr);
CCDelayTime *delay = CCDelayTime::create(1.0);
pSprite->runAction(CCSequence::create(fun1, delay, fun1, NULL));
The method I want to call:
void GameLayer::animateFlip(CCObject *pSObj, CCObject *pGObj){
CCSprite *pSprite = (CCSprite *) pSObj;
CCLabelTTF *pGetal = (CCLabelTTF *) pSObj;
...
...
}
The function is in the same class and requires two arguments. I've tried putting both arguments (CCSprite and CCLabelTTF) in an array, but it crashes on runtime...
When I call the function just like this no errors occur:
this->animateFlip(sprite1, getal1);
Anyone any idea?

Thanks for your answers, I've created a struct for my buttons like Joachim suggested, which has the sprite and the label in it. All the buttons are put in an array. I also added the functions animateFlip and showFlip to it. AnimateFlip works fine and I'm able to call the function from the gamelayer for each indevidial button.
void GameLayer::ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{
CCTouch *touch = (CCTouch *)pTouches->anyObject();
CCPoint location = touch->getLocationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
for(int i = 0; i < 12; i++){
if(butArr[i].sprite->boundingBox().containsPoint(location)){
butArr[i].animateFlip();
break;
}
}
}
The struct:
struct Button
{
cocos2d::CCSprite *sprite;
cocos2d::CCLabelTTF *getal;
int getalINT;
void showFlip();
void animateFlip();
};
But as rule number one in programming tells us, where one problem is solved, two shall arise, I've stumbled upon a new problem:
void Button::showFlip()
{
CCFiniteTimeAction *fun1 = CCCallFunc::create(this, callfunc_selector(Button::animateFlip));
CCFiniteTimeAction *fun1 = CCCallFunc::create(this, callfunc_selector(Button::animateFlip));
CCDelayTime *delay = CCDelayTime::create(1.0f);
this->runAction(CCSequence::create(fun1, delay, fun2, NULL));
}
The CCCallFunc::create() request a context (I guess?), which is usually 'this', but 'this' in my struct point to Button. How can I get the context of the gamelayer?
Thanks again!

Related

Getting ProtoBuf.ProtoException using OsmSharp in Xamarin Android

I am trying to test a sample project called Android.Routing.Offline from OsmSharp.Samples in Github.
After two taps on the screen (the first one gets just the GeoCoordinate) I get a ProtoBuf.ProtoException in the Router.cs
private static IBasicRouterDataSource<CHEdgeData> _graph;
public static void Initialize()
{
var routingSerializer = new CHEdgeDataDataSourceSerializer();
_graph = routingSerializer.Deserialize(
Assembly.GetExecutingAssembly().GetManifestResourceStream(#"Android.Routing.Offline.kempen-big.contracted.mobile.routing"));
}
public static Route Calculate(GeoCoordinate from, GeoCoordinate to)
{
try
{
lock(_graph)
{
var router = Router.CreateCHFrom(_graph, new CHRouter(), new OsmRoutingInterpreter());
// The exception happens here below
var fromResolved = router.Resolve(Vehicle.Car, from);
var toResolved = router.Resolve(Vehicle.Car, to);
if(fromResolved != null && toResolved !=null)
{
return router.Calculate(Vehicle.Car, fromResolved, toResolved);
}
}
}
catch(Exception ex)
{
OsmSharp.Logging.Log.TraceEvent("Router", OsmSharp.Logging.TraceEventType.Critical, "Unhandled exception occured: {0}", ex.ToString());
}
return null;
}
And the exception:
> {ProtoBuf.ProtoException: Invalid wire-type; this usually means you
> have over-written a file without truncating or setting the length; see
> http://stackoverflow.com/q/2152978/23354 at
> ProtoBuf.ProtoReader.ReadSingle () ...
I didnt overwrite the file (kempen-big.contracted.mobile.routing) just added it as a linked file in the project. Any ideas how I can solve this issue?
Well, the first thing to try is to check that the contents of the Stream you are reading (via GetManifestResourceStream) contains exactly the contents you are expecting, and not some wrapper or otherwise-corrupt mess. If you have some checksum algorithm you can run: great! Checking just the .Length would be a great start. Otherwise, you could cheat (just for the purposes of validating the contents) by getting the hex:
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
string hex = BitConverter.ToString(
ms.GetBuffer(), 0, (int)ms.Length);
// dump this string, and compare it to the same output run on the
// oringal file; they should be identical
}
Note that this duplicates the contents in-memory, purely so we can get a byte[] (oversized) to get the hex from - it isn't intended for "real" code, but until you are sure that the contents are correct, all other bets are off. I strongly suspect that you'll find that the contents are not identical to the contents in the original file. Note that I'm also implicitly assuming that the original file works fine in terms of deserialization. If the original file doesn't work: again, all bets are off.

Is calling a script in unityscript slow?

My enemy script is linked to a prefab and being instantiated by my main script.
It kills enemies in a random order (I am jumping on them and some are not dying, not what I want).
(what I am trying to achieve is an enemy to die when I jump on its head and play a death animation.
So from this enemy script I call the other script jump <-- which is linked to my player script and get the jump Boolean value. Could the processing of jump be to slow? I need help
I tried everything)
it works but only on certain enemies any ideas why? Thanks community.
Can anyone help me find a better method?
Could someone help me maybe find if the Players y => an amount to change jump var on the enemy
Just had a perfect run, whats wrong with this its working then not then it is partly working
If I add audio, it doesn't work.
#pragma strict
var enemy : GameObject;
var speed : float = 1.0;
var enemanim : Animator;
var isdying : boolean = false;
private var other : main;
var playerhit: boolean = false;
function Start () {
other = GameObject.FindWithTag("Player").GetComponent("main");
this.transform.position.x = 8.325;
this.transform.position.y = -1.3;
enemanim = GetComponent(Animator);
enemanim.SetFloat("isdead",0);
}
function OnCollisionEnter2D(coll: Collision2D) {
if(coll.gameObject.CompareTag("distroy")){
Destroy(enemy.gameObject);
}
if(coll.gameObject.CompareTag("Player")){
playerhit=true;
}
}
function Update () {
if(other.jumped === true && playerhit==true){ *****the jumped i need
enemanim.SetFloat("isdead",1);
}
}
function FixedUpdate(){
this.transform.Translate(Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0, 0));
this.rigidbody2D.velocity = Vector2(-5,0);
}
if(other.jumped === true && playerhit==true)
Is wrong.
It should be:
if(other.jumped == true && playerhit==true)
All 3 languages used by Unity, C#, UnityScript, and Boo, are compiled into the same IL byte code at the end. However, there are cases where UnityScript has some overhead as Unity does things in the background. One of these is that it does wrapping of access to members of built-in struct-properties like transform.position.
I prefer C#, I think it is better.

Sending boolean to Pebble with PebbleKit

I've never really done much C and am a bit stumped on the best way to send a boolean from an Android app to the Pebble Watch.
I have strings working fine, but there doesn't seem to be an addBoolean method on PebbleDictionary. As a work around I am trying to use addUint8 to send a 1 or 0, but am having trouble handling the message on the Pebble.
Here is my Android code:
PebbleDictionary data = new PebbleDictionary();
if (isGPSFix()){
data.addUint8(GPS_HAS_FIX_KEY, Byte.valueOf("1"));
} else {
data.addUint8(GPS_HAS_FIX_KEY, Byte.valueOf("0"));
}
PebbleKit.sendDataToPebble(app.getContext(), UUID, data);
And in my Pebble I have a data struct:
static struct MyData {
uint8_t haveGPS[1];
.... // other stuff ommitted
AppSync sync;
uint8_t sync_buffer[256];
} s_data;
And then I am trying to compare it like this in my sync_tuple_changed callback.
static void sync_tuple_changed_callback(const uint32_t key, const Tuple* new_tuple, const Tuple* old_tuple, void* context) {
(void) old_tuple;
switch (key) {
case GPS_HAS_FIX_KEY:
if (memcmp(s_data.haveGPS, new_tuple->value->data, 8) == 0){
memcpy(s_data.haveGPS,new_tuple->value->data, new_tuple->length);
vibes_short_pulse();
}
break;
default:
return;
}
}
The watch doesn't crash, it just never vibrates when the phone drops or acquires GPS.
Things look good on the Android side. I think this is more of an AppSync problem.
Here are a few things to check in the watch application:
Make sure you create a list of tuples with initial values on the watch. This list needs to to contain your key GPS_HAS_FIX_KEY;
Tuplet initial_values[] = {
TupletInteger(GPS_HAS_FIX_KEY, (uint8_t) 0),
/* Other tuplets that you will synchronize */
};
Make sure you pass those tuplets to the app_sync_init() function:
app_sync_init(&sync, sync_buffer, sizeof(sync_buffer),
initial_values, ARRAY_LENGTH(initial_values),
sync_tuple_changed_callback, sync_error_callback, NULL);
Those two steps are required for app_sync to work (cf AppSync reference documentation).
As far as I understand you have to send an Dictionary of keys and objects to the watch. In Objective C it looks like this:
NSDictionary *update = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
Keys are all integer and objects I would think can be of Boolean. In my case only String what works well.
In a loop I perform something like this on the watch:
t=dict_find(received,count);
strcpy(strs[count], dict_find(received,count)->value->cstring);
But I have to tell you that I am still a rookie.
Thanks to sarfata's accepted answer above, I found that I had not added this new item to the Tuple that the Pebble was expecting.
Once I added that, my switch statement started working and I just had to get the memory compare to work. Here is the working code for my memory compare in case it helps anyone.
case GPS_HAS_FIX_KEY:
if (memcmp(s_data.haveGPS, new_tuple->value->data, 1) != 0){
memcpy(s_data.haveGPS,new_tuple->value->data, 1);
vibes_short_pulse();
}
break;
It really was a simple as expecting one byte (not 8 bytes - I thought it was doing a bit compare) and negating the logic for the case where the new value is NOT like the old one.

How to use prismatic joint in Box2d for android

I am new to Box2d and have a situation where I have two bodies. One is static and the other is dynamic. I want my dynamic body to go down wards and come back and hit the other body along same line. I thought to use prismatic joint after some initial study. I have looked into some example and written a piece of code in onLoadScene(). But nothing is moving. Here is the code:
#Override
public Scene onLoadScene()
{
.....
PrismaticJointDef prismaticJointDef = new PrismaticJointDef();
prismaticJointDef.initialize(bdy_holder, bdy_spring, bdy_holder.getWorldCenter(), new Vector2(1.0f, 0.0f));
prismaticJointDef.lowerTranslation = -5.0f;
prismaticJointDef.upperTranslation = 2.5f;
prismaticJointDef.enableLimit = true;
prismaticJointDef.maxMotorForce = 200.0f;
prismaticJointDef.motorSpeed = 10.0f;
prismaticJointDef.enableMotor = true;
prismaticJointDef.collideConnected = true;
prismatic_Joint = (PrismaticJoint)this.mPhysicsWorld.createJoint(prismaticJointDef);
}
Now I think the bodies should be moving when I run the application, but they are not movng. I am totally new and can't figure out the exact problem. Kindly guide me to the problem, solution and proper example of using this. Thanks.
try
prismaticJointDef.collideConnected = false;

android emulator restarts itself (ADT)

When i invoke a function which is described below, android emulator restarts from beginning.
The function is like that
int index = 0;
Position myPostion;
Position destPosition = roadInstruction.getInstructionAt(index).getEndAddr();
while(index<roadInstruction.getNumInstruction())
{
myPostion = getMyPosition();
while(!hasArrivedToDestination(myPostion, destPosition ))
{
myPostion = getMyPosition();
}
++index;
}
What is the reason?
It maybe because of the inner while loop, but i am not sure.

Categories

Resources