I am creating my first game with cocos2D. And I have a problem looking for help.
I want to create some selected numbers and falling down randomly.
so this is what I did for the programe.
In my HelloWorldLayer.m
-(id) init
{
if( (self=[super init]) ) {
screenSize = [CCDirector sharedDirector].winSize;
CCSprite* background = [CCSprite spriteWithFile:#"game.png"];
background.position = ccp(screenSize.width/2, screenSize.height/2);
[self addChild:background z:0];
operatorArray = [[NSMutableArray alloc] init];
fallingNumberArray = [[NSMutableArray alloc] init];
[[[CCDirector sharedDirector] scheduler] scheduleSelector:#selector(update:) forTarget:self interval:0.0 paused:NO];
// Falling Number Font Type & Position
fallingNumber = [CCLabelBMFont labelWithString:#"99" fntFile:#"MyHelveticaCondensed.fnt"];
fallingNumber.anchorPoint=ccp(0.5f,0.5f);
fallingNumber.position = ccp(160,180);
[self addChild:fallingNumber z:3];
}
return self;
}
I have a method to generate the color for the numbers
-(void) colorFallingNumber{
// FallingNumber random and color ------------- START CODE -------------
do {
fallNum = (arc4random() % 60) + 1;
}
while ( fallNum == 23 || fallNum == 29 || fallNum == 31 || fallNum == 35 || fallNum == 37 || fallNum == 41 || fallNum == 43|| fallNum == 44|| fallNum == 46|| fallNum == 47|| fallNum == 49 || fallNum == 52|| fallNum == 53 || fallNum == 55 || fallNum == 56 || fallNum == 58|| fallNum == 59);
if (fallNum == 1 ||fallNum == 7 ||fallNum == 13 ||fallNum == 19 ||fallNum == 26 ||fallNum == 34 ||fallNum == 45 ||fallNum == 60) {
fallingNumber.color = ccc3(217,101,75);
}
if (fallNum == 2 ||fallNum == 8 ||fallNum == 14 ||fallNum == 20 ||fallNum == 27 ||fallNum == 36 ||fallNum == 48) {
fallingNumber.color = ccc3(79,166,134);
}
if (fallNum == 3 ||fallNum == 9 ||fallNum == 14 ||fallNum == 21 ||fallNum == 28 ||fallNum == 38 ||fallNum == 50) {
fallingNumber.color = ccc3(217,148,15);
}
if (fallNum == 4 ||fallNum == 10 ||fallNum == 16 ||fallNum == 22 ||fallNum == 30 ||fallNum == 39 ||fallNum == 51) {
fallingNumber.color = ccc3(209,75,217);
}
if (fallNum == 5 ||fallNum == 11 ||fallNum == 17 ||fallNum == 24 ||fallNum == 32 ||fallNum == 40 ||fallNum == 54) {
fallingNumber.color = ccc3(75,149,217);
}
if (fallNum == 6 ||fallNum == 12 ||fallNum == 18 ||fallNum == 25 ||fallNum == 33 ||fallNum == 42 ||fallNum == 57) {
fallingNumber.color = ccc3(217,75,32);
}
}
And this is update method
-(void) update:(ccTime)dt{
NSMutableArray* removeArray = [NSMutableArray array];
[self colorFallingNumber];
fallingNumber.string = [NSString stringWithFormat:#"%d",fallNum];
NSString *fallingNumberName = [NSString stringWithFormat:#"%d",fallNum]; ////// I think here is the problem
FallingNumber *newFallingNumber = [[NSClassFromString(fallingNumberName) alloc] init]; ////// I think here is the problem
[newFallingNumber animateFallingNumber];
newFallingNumber.scale = 1;
//newFallingNumber.rotation = atan2(newFallingNumber.direction.x,newFallingNumber.direction.y) * 180.0 / M_PI;
[fallingNumberArray addObject:newFallingNumber];
[self addChild:newFallingNumber z:4.0];
for(FallingNumber* fnumber in fallingNumberArray){
fnumber.position = ccp(fnumber.position.x + fnumber.speed *
fnumber.direction.x ,fnumber.position.y + fnumber.speed * fnumber.direction.y);
if(!CGRectContainsPoint(CGRectMake(-80,-80,320+160,480+160), fnumber.position)){
[self removeChild:fnumber cleanup:YES];
[removeArray addObject:fnumber];
}
}
// Operator animation ------------- START CODE -------------
if(RANDOM_FLOAT() < 0.1 && [operatorArray count] < 15){
NSString *operatorName = [NSString stringWithFormat:#"operator0%d.png", ((arc4random() % 4)+1)];
Operator* newOperator = [Operator spriteWithFile:operatorName];
[newOperator animateOperator];
newOperator.scale = 1;
newOperator.rotation = atan2(newOperator.direction.x,newOperator.direction.y) * 180.0 / M_PI;
[operatorArray addObject:newOperator];
[self addChild:newOperator z:2.0];
}
for(Operator* operator in operatorArray){
operator.position = ccp(operator.position.x + operator.speed *
operator.direction.x ,operator.position.y + operator.speed * operator.direction.y);
if(!CGRectContainsPoint(CGRectMake(-80,-80,320+160,480+160), operator.position)){
[self removeChild:operator cleanup:YES];
[removeArray addObject:operator];
}
} // Operator animation ------------- END CODE -------------
[operatorArray removeObjectsInArray:removeArray];
[removeArray removeAllObjects];
}
Also, I have create FallingNumber CCSprite in other file
It contains about the property of direction, speed...etc
Well, the problem is I cannot add the falling number object to the array. And I found that one of the reason is I use CCLabelBMFont to create the falling number.
Because it is work if i use png file, it works in Operator.
Looking for help.
This line,
FallingNumber *newFallingNumber = [[NSClassFromString(fallingNumberName) alloc] init];
Is confusing to me. It looks like you are trying to create an instance of the class FallingNumber, but by calling NSClassFromString(fallingNumberName) it looks like you are trying to instantiate a class that is literally called "16" or whatever the falling number happens to be.
From what I gather, it looks like you are just trying to pass the value of (fallingNumberName) to a new instance of the class FallingNumber. In that case, I would make a custom initalizer in FallingNumber that takes the parameter, such as this:
in FallingNumber.h:
-(id) initWithString:(NSString*)name;
Then you instantiate the class by making the following call:
FallingNumber *newFallingNumber = [[FallingNumber alloc] initWithString:fallingNumberName];
Then you have a new instance of the FallingNumber class with the value of the string that you want. Was this what you were looking for?
Related
An error sometimes occurs during program running.
It doesn't happen every time.
I don't know why I get an error in this part.
The length of strAckData is greater than 13
x_FWCommunity->sRevDataStr = strAckData.GetAt(13); '
User SourceCode
void CMLT2App::AckTotalFusingMsg(CString strAckData)
{
char szLog[512];
CString strCmd(""), strResult(""), strTemp(""), strLen("");
char cResult;
int nCmd = 0, nPos = 0, nDataLen = 0;
strTemp = strAckData;
nPos = strTemp.Find(0x02);
strAckData = strTemp.Mid(nPos, strAckData.GetLength() - nPos);
if (strAckData.GetAt(0) != 0x02) return; // Check STX
if (strAckData.GetAt((strAckData.GetLength() - 1)) != 0x03) // Check ETX
return;
strCmd.Format("%s", strAckData.Mid(7, 2)); // Get Command;
sscanf(strCmd, "%X", &nCmd); // String Convert to Hex
cResult = strAckData.GetAt(13); // String Convert to Decimal
x_FWCommunity->sRevCmdStr = strCmd;
strLen.Format("%s", strAckData.Mid(9, 4));
sscanf(strLen, "%X", &nDataLen);
// strCmd 는 0xBD
if (strCmd == "FE" || strCmd == "5E")
{
x_FWCommunity->sRevDataStr = strAckData.Mid(13, nDataLen);
// AfxMessageBox(x_FWCommunity->sRevDataStr);
}
else
x_FWCommunity->sRevDataStr = strAckData.GetAt(13); ← Error Point
switch (nCmd)
{
case CMD_CTRL_FUSING_SYSTEM:
case CMD_CTRL_FUSING_CONTROL_PTN:
case CMD_CTRL_FUSING_PREDISP_PTN:
Call Stack Log
MSVCRTD! 102136a8()
MSVCRTD! 102135b1()
operator delete(void * 0x01a11f28) line 351 + 12 bytes
CString::FreeData() line 146 + 15 bytes
CString::Release() line 157
CString::AllocBeforeWrite(int 1) line 200
CString::AssignCopy(int 1, const char * 0x01e2e684) line 315
CString::operator=(char 48) line 88
CMLT2App::AckTotalFusingMsg(CString {"A2A100BD002300375000011320373000000630331000000C3"}) line 6029
CMLT2App::RS232C_ReceivedFusingInfo(unsigned char * 0x01e2eb8c) line 5412
ThreadWatchComm1(CPortController * 0x01514010) line 966
KERNEL32! 7c7db729()
I am rather new to c++, and I am struggling to initialize a hook in my game hack. On the line where I am attempting to pattern scan a DLL from the game's files, I am getting the error in the title, they will be marked. If any more code needs to be provided LMK, I appreciate any help.
Code:
void hooks::initialize() {
const auto create_move_target = reinterpret_cast<void*>(get_virtual(interfaces::clientmode, 24));
const auto paint_traverse_target = reinterpret_cast<void*>(get_virtual(interfaces::panel, 41));
const auto lock_cursor_target = reinterpret_cast<void*>(get_virtual(interfaces::surface, 67));
original_wnd_proc = reinterpret_cast<WNDPROC>(SetWindowLongPtrA(FindWindowA("Valve001", nullptr), GWL_WNDPROC, reinterpret_cast<LONG>(menu::wnd_proc)));
if (MH_Initialize() != MH_OK)
throw std::runtime_error("failed to initialize MH_Initialize.");
if (MH_CreateHook(lock_cursor_target, &surface::lock_cursor, reinterpret_cast<void**>(&lock_cursor_original)) != MH_OK)
throw std::runtime_error("failed to initialize lock_cursor. (outdated index?)");
MH_CreateHook(**reinterpret_cast<void***>(utilities::pattern_scan(GetModuleHandleA("gameoverlayrenderer.dll"), "FF 15 ? ? ? ? 8B F8 85 FF 78 18") + 2), &menu::reset, reinterpret_cast<void**>(&reset_original)); //error at GetModuleHandleA
MH_CreateHook(**reinterpret_cast<void***>(utilities::pattern_scan(GetModuleHandleA("gameoverlayrenderer.dll"), "FF 15 ? ? ? ? 8B F8 85 DB") + 2), &menu::present, reinterpret_cast<void**>(&present_original)); //error at GetModuleHandleA
if (MH_CreateHook(create_move_target, &create_move::hook, reinterpret_cast<void**>(&create_move_original)) != MH_OK)
throw std::runtime_error("failed to initialize create_move. (outdated index?)");
if (MH_CreateHook(paint_traverse_target, &paint_traverse::hook, reinterpret_cast<void**>(&paint_traverse_original)) != MH_OK)
throw std::runtime_error("failed to initialize paint_traverse. (outdated index?)");
if (MH_EnableHook(MH_ALL_HOOKS) != MH_OK)
throw std::runtime_error("failed to enable hooks.");
console::log("[setup] hooks initialized!\n");
}
Thanks for taking the time to look as this question, I am very new to programming and am having a problem with the following error. Any help would be really appreciated.
I am currently learning via Ray Wenderlichs 'Learning Cocos2D' book but also experiment with the code to attempt to learn more and this is where I have run into a problem I can not fix.
I am using CocosDenshion to play the music tracks for the main menu and first gameplay scene, Ray advises in his book to call the following method from the GAMEPLAY SCENE...
[[GameManager sharedGameManager] playBackgroundTrack:BACKGOUND_TRACK_OLE_AWAKES];
This of course works but rather than call the above method in the gameplay scene I want to control the start and stopping of the music from my GameManager class.
So I want music to play in the menu and then nothing to play on the gameplay layer and to control it from one class.
To do this I have attempted to add the following in "GameManager.h.".
if (soundEngine.isBackgroundMusicPlaying == YES) {
[soundEngine stopBackgroundMusic];
}
In to the method below...
- (NSString*)formatSceneTypeToString:(SceneTypes)sceneID {
NSString *result = nil;
switch(sceneID) {
case kNoSceneUninitialized:
if ((soundEngine.isBackgroundMusicPlaying == YES)){
[soundEngine stopBackgroundMusic];
}
result = #"kNoSceneUninitialized";
break;
case kMainMenuScene:
if ((isSoundEffectsOn == YES)&&(soundEngine.isBackgroundMusicPlaying == NO)){
[self playBackgroundTrack:BACKGROUND_TRACK_MAIN_MENU];
} else if ((isSoundEffectsOn == NO)&&(soundEngine.isBackgroundMusicPlaying == YES)){
[soundEngine stopBackgroundMusic];
}
if (isMusicOn == YES) {
result = #"kMainMenuScene";
} else if (isMusicOn == NO) {
result = #"kNoSceneUninitialized";
// return NO;
}
break;
case kOptionsScene:
if ((isSoundEffectsOn == YES)&&(soundEngine.isBackgroundMusicPlaying == NO)){
[self playBackgroundTrack:BACKGROUND_TRACK_MAIN_MENU];
} else if ((isSoundEffectsOn == NO)&&(soundEngine.isBackgroundMusicPlaying == YES)){
[soundEngine stopBackgroundMusic];
}
if (isMusicOn == YES) {
result = #"kOptionsScene";
} else if (isMusicOn == NO) {
// return NO;
result = #"kNoSceneUninitialized";
}
break;
case kGameLevel1:
if ([soundEngine.isBackgroundMusicPlaying == YES]){
[soundEngine stopBackgroundMusic]; <--CRASHES HERE!
} else {
}
result = #"kGameLevel1";
break;
Now the above works fine for the MAIN MENU and OPTIONS screens when I run it but seems to crash when I attempt to load the GAMELEVEL1 screen. The crash only seems to occur once every now and then which is confusing to say the least.
When it crashes it takes me to the following in CDAudioManager.h..
-(BOOL) isPlaying {
if (state != kLAS_Init) {
return [audioSourcePlayer isPlaying]; <--Thread 18:EXC_BAD_ACCESS(code=1,address=0x8001400c)
} else {
return NO;
}
}
I also get the below in the console...
2014-10-28 12:46:03.948 SpaceViking[1807:343] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CCStandardTouchHandler isPlaying]: unrecognized selector sent to instance 0x7e013d80'
*** First throw call stack:
(
0 CoreFoundation 0x05bb25e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x025658b6 objc_exception_throw + 44
2 CoreFoundation 0x05c4f903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
3 CoreFoundation 0x05ba290b ___forwarding___ + 1019
4 CoreFoundation 0x05ba24ee _CF_forwarding_prep_0 + 14
5 SpaceViking 0x00183e72 -[CDLongAudioSource isPlaying] + 82
6 SpaceViking 0x00185425 -[CDAudioManager isBackgroundMusicPlaying] + 69
7 SpaceViking 0x0018ea60 -[SimpleAudioEngine isBackgroundMusicPlaying] + 48
8 SpaceViking 0x0019fe62 -[GameManager formatSceneTypeToString:] + 9634
9 SpaceViking 0x001a095e -[GameManager getSoundEffectsListForSceneWithID:] + 2302
10 SpaceViking 0x0019d50a -[GameManager unloadAudioForSceneWithID:] + 186
11 Foundation 0x01e39597 -[NSThread main] + 76
12 Foundation 0x01e394f6 __NSThread__main__ + 1275
13 libsystem_pthread.dylib 0x02d185fb _pthread_body + 144
14 libsystem_pthread.dylib 0x02d18485 _pthread_struct_init + 0
15 libsystem_pthread.dylib 0x02d1dcf2 thread_start + 34
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Sorry for the length of this question but wanted to try and include as much information as possible.
EDIT
I could be completely wrong but if the sound engine is called from 2 different classes would that cause this? As i have the following in the MainMenu layer...
-(void)playScene:(CCMenuItemFont*)itemPassedIn {
if ([itemPassedIn tag] == 1) {
CCLOG(#"Tag 1 found, mode");
if ([GameManager sharedGameManager].isSoundEffectsOn ==YES ) {
PLAYSOUNDEFFECT(BUTTONPRESS); <----Calling the sound engine to play a sound on button press.- this is unloading the sound as level1 starts.
[[GameManager sharedGameManager] runSceneWithID:kGameLevel1];
}else if ([GameManager sharedGameManager].isSoundEffectsOn ==NO ) {
[[GameManager sharedGameManager] runSceneWithID:kGameLevel1];
return;
}
I try to program a top-down-shooter in SFML at the moment, but ran into a problem. I'm quite new to C++ and programming in general, so please excuse messy code and/or overly complicated solutions.
I have two std::lists, one containing the randomly spawning enemies, the other containing the bullets I fired. When a bullet hits a enemy, both of them should get erased, but it doesn't work.
Here's the problem-part of my code:
for(MonsterIt = MonsterList.begin(); MonsterIt != MonsterList.end(); MonsterIt++)
{
//Here would be Monster-Movement
//Collision Monster-Player (MonsterIt = iterator of MonsterList)
if ((MonsterIt -> getPosition().x + 25) >= PlayerX - 25 &&
(MonsterIt -> getPosition().x - 25) <= PlayerX + 25 &&
(MonsterIt -> getPosition().y + 25) >= PlayerY - 25 &&
(MonsterIt -> getPosition().y - 25) <= PlayerY + 25 )
{
MonsterList.erase(MonsterIt);
break;
}
window.draw(*MonsterIt);
}
That's the way I've done collision between Monster and Player. That worked fine, so I tried the same with Monsters and Lasers:
for(LaserIt = LaserList.begin(); LaserIt != LaserList.end(); LaserIt++)
{
//Here would be "Laser-Movement"
//Collision-Laser // Doesn't work
if ((MonsterIt -> getPosition().x + 25) >= //
(LaserIt -> getPosition().x - 7) && //
(MonsterIt -> getPosition().x - 25) <= //
(LaserIt -> getPosition().x + 7) && //
(MonsterIt -> getPosition().y + 25) >= //
(LaserIt -> getPosition().y - 7) && //
(MonsterIt -> getPosition().y - 25) <= //
(LaserIt -> getPosition().x + 7)) //
{ //
MonsterList.erase(MonsterIt); //
//
LaserList.erase(LaserIt); //
//
break; //
} //
window.draw(*LaserIt);
}
When I put in the part of code I marked (with // on right side) I get a "list iterator not dereferencable"-error while debugging as soon as I shoot. When I cut out said code it runs fine (I can shoot, walk into monsters and they disappear, etc.). Because of that I guess the rest of my code is working.
So, is collision between iterators of different lists even possible?
And if so, how do I do it?
If you need more information or code, please ask. I'd be glad for your help...
The iterator you use is not valid.
There are several solutions to your problems. First one:
for(MonsterIt = MonsterList.begin(); MonsterIt != MonsterList.end(); MonsterIt++)
{
//Here would be Monster-Movement
//Collision Monster-Player (MonsterIt = iterator of MonsterList)
// Collision with laser, inside the loop for monsters
for(LaserIt = LaserList.begin(); LaserIt != LaserList.end(); LaserIt++)
{
}
window.draw(*MonsterIt);
}
This solution is not really C++ish. With OOP, you can have a much clearer code:
class Player
{
public:
int X, Y; // for code simplicity on SO.
};
// ...
Player player;
for(MonsterIt = MonsterList.begin(); MonsterIt != MonsterList.end(); MonsterIt++)
{
MonsterIt->update(player,LaserList);
if(!MonsterIt->isAlive())
{
// Remove monster from list *without* break
}
}
Then, Monster is a class like the following:
class Monster
{
bool alive;
public:
bool isAlive() const { return alive; }
bool collideWithPlayer(Player p) const
{
// Returns whether it collide with player
// ...
}
bool collideWithLaser(Laser l) const
{
// Returns whether it collide with one laser
// ...
}
bool collideWithLasers(LaserList l) const
{
for(LaserIt = LaserList.begin(); LaserIt != LaserList.end(); LaserIt++)
if(collideWithLaser(*LaserIt))
return true;
return false;
}
void update(Player p, LaserList l)
{
if(collideWithPlayer(p) || collideWithLasers(l))
alive = false;
else
window.draw(this);
}
};
I am filtering the HKEYS by using Hook filtering function, I use the following code to disable Alt+Tab, Alt+Esc, Ctrl+Esc, Windows Key
if (((lParam.vkCode == 9) && (lParam.flags == 32))||
((lParam.vkCode == 27) && (lParam.flags == 32))||
((lParam.vkCode == 27) && (lParam.flags == 0)) ||
((lParam.vkCode == 91) && (lParam.flags == 1)) ||
((lParam.vkCode == 92) && (lParam.flags == 1)) ||
((true) && (lParam.flags == 32)))
return 1;
Can any one tell me how can I disable Ctrl+Alt+Del? I have tried a lot to filter this but unsuccessful for me.
I have got answer of my own question, ctrl+alt+del can't filter out from hook, the only way to disable ctrl+alt+del is to modify the registry form your code..