Daily Archives

Articles indexed Saturday July 7 2012

Page 7/15 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Box 2D Collision Question

    - by Farooq Arshed
    I am very new to Box 2D Physics world. I wanted to know how to collide 2 bodies when one is Dynamic and other is Kinematic. The whole Scenario is explained below: I have 3 balls in total. I want to balls to remain in their places and the third ball to be able to move. When the third ball hits the other two balls then they should move according to the speed and direction from which they were hit. My gravity of the world is 0 because I only want z-axis gravity. I would also like some one to point me towards some good tutorials regarding Box 2D basics which is language independent. I hope I have explained my scenario well. Thanks for the help in advance.

    Read the article

  • How can I teleport seamlessly, without using interpolation?

    - by modchan
    I've been implementing Bukkit plugin for creating toggleable in-game warping areas that will teleport any catched entity to other similar area. I was going to implement concept of non-Euclidean maze using this plugin, but, unfortunately, I've discovered that doing Entity.teleport() causes client to interpolate movement while teleporting, so player slides towards target like Enderman and receives screen updates, so for a split second all underground stuff is visible. While for "just teleport me where I want" usage this is just fine, it ruins whole idea of seamless teleporting, as player can clearly see when transfer happened even without need to look at debug screen. Is there possibility to somehow disable interpolating while teleporting without modifying client, or maybe prevent client from updating screen while it's being teleported?

    Read the article

  • glutPostRedisplay() does not update display

    - by A D
    I am currently drawing a rectangle to the screen and would like to move it by using the arrow keys. However, when I press an arrow key the vertex data changes but the display does refresh to reflect these changes, even though I am calling glutPostRedisplay(). Is there something else that I must do? My code: #include <GL/glew.h> #include <GL/freeglut.h> #include <GL/freeglut_ext.h> #include <iostream> #include "Shaders.h" using namespace std; const int NUM_VERTICES = 6; const GLfloat POS_Y = -0.1; const GLfloat NEG_Y = -0.01; struct Vertex { GLfloat x; GLfloat y; Vertex() : x(0), y(0) {} Vertex(GLfloat givenX, GLfloat givenY) : x(givenX), y(givenY) {} }; Vertex left_paddle[NUM_VERTICES]; void init() { glClearColor(1.0f, 1.0f, 1.0f, 0.0f); left_paddle[0] = Vertex(-0.95f, 0.95f); left_paddle[1] = Vertex(-0.95f, 0.0f); left_paddle[2] = Vertex(-0.85f, 0.95f); left_paddle[3] = Vertex(-0.85f, 0.95f); left_paddle[4] = Vertex(-0.95f, 0.0f); left_paddle[5] = Vertex(-0.85f, 0.0f); GLuint vao; glGenVertexArrays( 1, &vao ); glBindVertexArray( vao ); GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(left_paddle), NULL, GL_STATIC_DRAW); GLuint program = init_shaders( "vshader.glsl", "fshader.glsl" ); glUseProgram( program ); GLuint loc = glGetAttribLocation( program, "vPosition" ); glEnableVertexAttribArray( loc ); glVertexAttribPointer( loc, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindVertexArray(vao); } void movePaddle(Vertex* array, GLfloat change) { for(int i = 0; i < NUM_VERTICES; i++) { array[i].y = array[i].y + change; } glutPostRedisplay(); } void special( int key, int x, int y ) { switch ( key ) { case GLUT_KEY_DOWN: movePaddle(left_paddle, NEG_Y); break; } } void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, 6); glutSwapBuffers(); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(500,500); glutCreateWindow("Rectangle"); glewInit(); init(); glutDisplayFunc(display); glutSpecialFunc(special); glutMainLoop(); return 0; }

    Read the article

  • Should the main game object be static in c++

    - by Som_kun
    I am creating a 2d platformer using SDL and I was thinking that my game object could be static, but I wasn't sure if this was a good idea. The pros (that I can see): Accessing settings options (such as screen size and keyboard bindings) would be easier accessed There should only ever be one main game loop, so this makes sure for me. The cons: From what I've heard, static classes in C++ are a bear to work with I've read that this may cause problems later in development (things don't work right or can't be used properly

    Read the article

  • 2D Rendering with OpenGL ES 2.0 on Android (matrices not working)

    - by TranquilMarmot
    So I'm trying to render two moving quads, each at different locations. My shaders are as simple as possible (vertices are only transformed by the modelview-projection matrix, there's only one color). Whenever I try and render something, I only end up with slivers of color! I've only done work with 3D rendering in OpenGL before so I'm having issues with 2D stuff. Here's my basic rendering loop, simplified a bit (I'm using the Matrix manipulation methods provided by android.opengl.Matrix and program is a custom class I created that just calls GLES20.glUniformMatrix4fv()): Matrix.orthoM(projection, 0, 0, windowWidth, 0, windowHeight, -1, 1); program.setUniformMatrix4f("Projection", projection); At this point, I render the quads (this is repeated for each quad): Matrix.setIdentityM(modelview, 0); Matrix.translateM(modelview, 0, quadX, quadY, 0); program.setUniformMatrix4f("ModelView", modelview); quad.render(); // calls glDrawArrays and all I see is a sliver of the color each quad is! I'm at my wits end here, I've tried everything I can think of and I'm at the point where I'm screaming at my computer and tossing phones across the room. Anybody got any pointers? Am I using ortho wrong? I'm 100% sure I'm rendering everything at a Z value of 0. I tried using frustumM instead of orthoM, which made it so that I could see the quads but they would get totally skewed whenever they got moved, which makes sense if I correctly understand the way frustum works (it's more for 3D rendering, anyway). If it makes any difference, I defined my viewport with GLES20.glViewport(0, 0, windowWidth, windowHeight); Where windowWidth and windowHeight are the same values that are pased to orthoM It might be worth noting that the android.opengl.Matrix methods take in an offset as the second parameter so that multiple matrices can be shoved into one array, so that'w what the first 0 is for For reference, here's my vertex shader code: uniform mat4 ModelView; uniform mat4 Projection; attribute vec4 vPosition; void main() { mat4 mvp = Projection * ModelView; gl_Position = vPosition * mvp; } I tried swapping Projection * ModelView with ModelView * Projection but now I just get some really funky looking shapes... EDIT Okay, I finally figured it out! (Note: Since I'm new here (longtime lurker!) I can't answer my own question for a few hours, so as soon as I can I'll move this into an actual answer to the question) I changed Matrix.orthoM(projection, 0, 0, windowWidth, 0, windowHeight, -1, 1); to float ratio = windowWwidth / windowHeight; Matrix.orthoM(projection, 0, 0, ratio, 0, 1, -1, 1); I then had to scale my projection matrix to make it a lot smaller with Matrix.scaleM(projection, 0, 0.05f, 0.05f, 1.0f);. I then added an offset to the modelview translations to simulate a camera so that I could center on my action (so Matrix.translateM(modelview, 0, quadX, quadY, 0); was changed to Matrix.translateM(modelview, 0, quadX + camX, quadY + camY, 0);) Thanks for the help, all!

    Read the article

  • IPhone iOs 5, need help getting my tab bar at the top to work

    - by Patrick
    I wanted to have the tab bar at the top. So i created a new project in XCode. Added a view and then inside that view i added (scrollbar, text and another view). See picture. What i wanted was to have my tab bar at the top. Then in the middle would be the contents from the tab bar and below it a small copyright text. See picture. No idea how to make this correctly. I have tried to create the UITabBarController on the fly and then assign it into the view at the top. (Top white space on the picture dedicated for the tab bar). Here is my code to init the MainWindow. MainWindow.h #import <UIKit/UIKit.h> @class Intro; @interface MainWindow : UIViewController @property (strong, nonatomic) IBOutlet UIScrollView *mainContentFrame; @property (strong, nonatomic) IBOutlet UIView *mainTabBarView; @property (strong, nonatomic) UITabBarController *mainTabBar; @property (nonatomic, strong) Intro *intro; // Trying to get this tab to show in the tab bar @end MainWindow.m #import "MainWindow.h" #import "Intro.h" @interface MainWindow () @end @implementation MainWindow @synthesize mainContentFrame = _mainContentFrame; @synthesize mainTabBarView = _mainTabBarView; @synthesize mainTabBar = _mainTabBar; @synthesize intro = _intro; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { _intro = [[Intro alloc] init]; NSArray *allViews = [[NSArray alloc] initWithObjects:_intro, nil]; [super viewDidLoad]; // Do any additional setup after loading the view. _mainTabBar = [[UITabBarController alloc] init]; [_mainTabBar setViewControllers:allViews]; [_mainTabBarView.window addSubview:_mainTabBar.tabBarController.view]; } - (void)viewDidUnload { [self setMainTabBar:nil]; [self setMainContentFrame:nil]; [self setMainContentFrame:nil]; [super viewDidUnload]; // Release any retained subviews of the main view. } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } @end What am i missing to get this to work? Wanted the content to end up in the scrollview so that all tabs are scrollable.

    Read the article

  • Can't get values from Sqlite DB using query

    - by Sana Joseph
    I used sqlite to populate a DB with some Tables in it. I made a function at another javascript page that executes the database & selects some values from the table. Javascript: function GetSubjectsFromDB() { tx.executeSql('SELECT * FROM Subjects', [], queryNSuccess, errorCB); } function queryNSuccess(tx, results) { alert("Query Success"); console.log("Returned rows = " + results.rows.length); if (!results.rowsAffected) { console.log('No rows affected!'); return false; } console.log("Last inserted row ID = " + results.insertId); } function errorCB(err) { alert("Error processing SQL: "+err.code); } Is there some problem with this line ? tx.executeSql('SELECT * FROM Subjects', [], queryNSuccess, errorCB); The queryNSuccess isn't called, neither is the errorCB so I don't know what's wrong.

    Read the article

  • issue with keychain and updates from app store

    - by xonegirlz
    I am having a very frustrating error. I have tested for an app upgrade by first installing the previous version (1.0.1) and then running version (1.0.2). Everything worked fine. I submitted the app and then I am getting issues people are getting crashes when they upgrade. I tried doing the same thing, which is installing the 1.0.1 and then install the binary on the app store, then it crashed. I looked at the console and crash logs and I get this: Jul 7 08:07:45 unknown MyApp[1429] <Warning>: KeychainUtils keychainValueForKey: - Error finding keychain value for key. Status code = -25300 Jul 7 08:07:45 unknown MyApp[1429] <Warning>: AccountSession readUserDataFromDisk - Error finding keychain value for key /var/mobile/Applications/997B32E7-6FFC-4696-9CAA-129BADE2FE64/Documents/instagram_json Jul 7 08:07:45 unknown MyApp[1429] <Warning>: UISegmentedControlStyleBezeled is deprecated. Please use a different style. Jul 7 08:07:45 unknown MyApp[1429] <Error>: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: username)' *** First throw call stack: (0x33ee688f 0x367e7259 0x33ee6789 0x33ee67ab 0x33e5368b 0x14fd99 0x152319 0x1530bb 0x170299 0x3270ec59 0x32711817 0x354e7dfb 0x354e7cd0) Jul 7 08:07:45 unknown UIKitApplication:com.firesnakelabs.pinstagram[0x14e4][1429] <Notice>: terminate called throwing an exception >

    Read the article

  • Class Method not working in objective c

    - by byteSlayer
    In my code I have a class called 'ProfileShareViewController', In which I have imported another class I have created called 'OwnProfileData', And I have also created an Instance of that class (class = OwnProfileData) as a property Of 'ProfileShareViewController' and synthesized it (instance called 'OwnProfile'). In another class I have called 'EditProfileViewController', I have imported the 'ProfileShareViewController', and now I am trying to change a property of the OwnProfile object from the ProfileShareViewController within the EditProfileViewController class. For some reason that doesn't work. I have Tried typing: [[ProfileShareViewController ownProfile] setName:@"Ido"]; (The property I am trying to set is Name, and as it is synthesized in OwnProfileData, I am using 'setName'). This doesn't work and I get the warning: "No known class method for selector 'ownMethod'. Any Idea as for why that might happen and how I can fix this? Thanks for your comments! Any support is highly appreciated!

    Read the article

  • Open Graph & Rails not retrieving object's URL

    - by Fred
    I'm using Rails to try and add an action for an object both defined for my app on the open graph. I am using an :after_filter in my controller to call the following after session#create: @graph.put_connections('me', 'workkout:complete', :session => url_for([@plan, @session])) I am getting the following back from Facebook: {"error":{"type":"Exception","message":"Could not retrieve data from URL.","code":1660002}} I have checked that the correct URL is passed to put_connections, and when I visit this URL using Facebook's Lint tool, everything is correct. I can't understand why this isn't working, my only thought is that Facebook is hitting the URL moments before rails has generated the object? - not sure if that's even possible though. Can anyone shed any light on this?

    Read the article

  • How to call JS function within .js file into .jsp file?

    - by Simple-Solution
    I am trying to call a javaScript function that's in .../js/index.js file to .../index.jsp file. Any suggestion would be helpful. Here is code within both file: index.js function testing() { if ("c" + "a" + "t" === "cat") { document.writeln("Same"); } else { document.writeln("Not same"); }; }; index.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <script type="text/javascript" src="js/index.js"> <!-- I want to call testing(); function here --> </script> </body> </html>

    Read the article

  • ios - how do I concatinate strings to create a url?

    - by GeekedOut
    I am trying to make a url by first collecting the parameters, and then in one statement creating the actual url. Here is what I am trying to do: NSString *urlString = @"http://www.some_login_url.com?email=%@&password=%@"; NSString *email = self.email.text; NSString *password = self.password.text; NSString *url_to_send = [NSString stringWithFormat:@"%@%@", urlString , email , password]; So what I wanted to do was replace the @ symbols with the values in the variables, but instead the second variable just got appended to the end of the string. How would I change the last line so I could put the right parameters in their correct spots? Thanks!!

    Read the article

  • Define background Image with UIImage

    - by Wohoo Summer
    I am using header file to set the background for my application and I have something like #define backgroundImage [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.jpeg"]] but I want use UIImageView instead of UIColor. I know I can do: UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) [imageView setImage:[UIImage imageNamed:@"background.png"]]; self.tableView.backgroundView = imageView; but how do I use it with #define?

    Read the article

  • Expected symbol problems with this function declaration

    - by Derek
    I am just getting back into the C programming realm and I am having an issue that I think is linker related. I am using cmake for the first time as well, so that could be adding to my frustration. I have included a third party header file that contains a typedef that my code is trying to use, and it has this line: typedef struct a a_t so my code has a_t *var; //later..... var->member;// this line throws the error which throws the error: dereferencing pointer to incomplete type So am I just missing another include file, or is this a linker issue? I am building this code in QtCreator and using cmake. I can dive on a_t to see that typedef declaration in the included header, but I can't seem to dive on "struct a" itself to see where it's coming from. Thanks

    Read the article

  • Strange type in c++

    - by Cemre
    I have a method with the prototype: bool getAssignment(const Query& query, Assignment *&result); I am a bit confused about the type of the second param (Assignment *&result) since I don't think I have seen something like that before. It is used like: Assignment *a; if (!getAssignment(query, a)) return false; Is it a reference to a pointer or the other way around ? or neither ? Any explanation is appreciated. Thanks.

    Read the article

  • MySQL Query - WHERE and IF?

    - by Prash
    I'm not quite sure how to right this query. Basically, I'm going to have a table with two columns (OS and country_code) - more columns too, but those are the conditional ones. These will be either set to 0 for all, or specific ones, separated by commas. Now, what I'm trying achieve is pull data from the table if the OS and country_code = 0, or if they contain matching data (separated by commas). Then, I have a column for time. I want to select rows where the time is GREATER than the time column, unless the column time_t is set to false, in which case this shouldn't matter. I hope I explained it right? This is what I kind of have so far: $get = $db->prepare("SELECT * FROM commands WHERE country_code = 0 OR country_code LIKE :country_code AND OS = 0 OR OS LIKE :OS AND IF (time_t = 1, expiry > NOW()) "); $get->execute(array( ':country_code' => "%{$data['country_code']}%", ':OS' => "%{$data['OS']}%" ));

    Read the article

  • Plot numpy datetime64 with matplotlib

    - by enedene
    I have two numpy arrays 1D, one is time of measurement in datetime64 format, for example: array([2011-11-15 01:08:11, 2011-11-16 02:08:04, ..., 2012-07-07 11:08:00], dtype=datetime64[us]) and other array of same length and dimension with integer data. I'd like to make a plot in matplotlib time vs data. If I put the data directly, this is what I get: plot(timeSeries, data) Is there a way to get time in more natural units? For example in this case months/year would be fine.

    Read the article

  • Custom StyleCop rule not working as expected

    - by Jon
    I'm trying to write a StyleCop rule that disallows underscores anywhere. There is a rule to say that you cant have public string _myfield but I don't want underscores anywhere ie/method names, property names, method parameters. Below is my code but its not working properly. Can anyone suggest why? using Microsoft.StyleCop; using Microsoft.StyleCop.CSharp; namespace DotNetExtensions.StyleCop.Rules { [SourceAnalyzer(typeof(CsParser))] public class NoUnderScores : SourceAnalyzer { public override void AnalyzeDocument(CodeDocument document) { CsDocument csdocument = (CsDocument) document; if (csdocument.RootElement != null && !csdocument.RootElement.Generated) csdocument.WalkDocument(new CodeWalkerElementVisitor<object>(this.VisitElement), null, null); } private bool VisitElement(CsElement element, CsElement parentElement, object context) { if (!element.Generated) { foreach(var token in element.Tokens) { if (token.Text.Contains("_")) AddViolation(element, "NoUnderScores"); } } return true; } } }

    Read the article

  • How to pass an integer to create new variable name?

    - by Joe
    I have 50 svg animations named animation0, animation1, animation2 etc. and I want to load them when the integer 0 to 49 is passed to this function: function loadAnimation(value){ var whichswiffy = "animation" + value; var stage = new swiffy.Stage(document.getElementById('swiffycontainer'), whichswiffy); stage.start(); } It doesn't work at the moment, maybe it's passing 'whichswiffy' rather than 'animation10'? Any ideas?

    Read the article

  • layout problems with site

    - by user1506962
    I have a problem with my site. When I resize the window everything stays still and doesn't move, the window just crosses over everything. Here are the images to epxlain it a bit better.. hopefully. This is the site in normal window - http://imageshack.us/photo/my-images/407/problem2a.jpg/ and when resized - http://imageshack.us/photo/my-images/696/problemim.jpg/ Can anyone tell me what the problem is? I would like my layout to work like this website - http://www.thisoldbear.com/ -----EDIT----- body { width: 1400px; -ms-overflow-x: hidden; overflow-x: hidden; background: url(../../core/images/bg.png); font-family: 'Pontano Sans', sans-serif; } #logo { background: url(../../core/images/logo.png); width: 124px; height: 171px; margin: -86px 185px; } nav { margin: 0 300px; } a { text-decoration: none; font-size: 17px; color: #f4f4f4; outline: none; padding-left: 50px; } a:hover { text-decoration: underline; } p { font-size: 22px; color: #444; } h2 { font-size: 29px; color: #444; } header { background: url(../../core/images/header.png); padding: 32px; margin: -8px -8px; } .content { padding: 10px; width: 700px; border-top: 4px solid #d55d58; margin: 100px 200px; } .break { margin: -50px 0; }

    Read the article

  • Dividing numbers between rows in MySQL + PHP

    - by André Figueira
    Hi I am working on a kind of raffle system which divides 1 million random numbers into an x amount of tickets, e.g. 1 million random numbers to 10,000 tickets. Each ticket is a row in a database, we then have another table ticket numbers in which i need to give 100 numbers to each ticket they are related by the ticket id. So at the moment this is my code: //Amount of the 1 million tickets divided to the tickets $numbersPerTickets = $_POST['numbersPerTicket']; //The total cost of the property $propertyPrice = $_POST['propertyPrice']; //The total amount of tickets $totalTickets = NUMBER_CIELING / $numbersPerTickets; //The ticket price $ticketPrice = $propertyPrice / $totalTickets; //Generate array with random numbers up to 999,999 $randomTicketNumbers = createTicketNumbers(); //Creation loop counter $ticketCreationCount = 1; //Loop and create each ticket while($ticketCreationCount <= $totalTickets) { //Create a padded ticket number $ticketNumber = str_pad($ticketCreationCount, 6, 0, STR_PAD_LEFT); $query = ' INSERT INTO tickets( propertyID, ticketNumber, price ) VALUES( "'.$propertyID.'", "'.$ticketNumber.'", "'.$ticketPrice.'" ) '; $db->query($query); //Get the ID of the inserted ticket to use to insert the ticket numbers $ticketID = $db->insert_id; $loopBreak = $numbersPerTickets; $addedNumberCount = 1; foreach($randomTicketNumbers as $key => $value) { $query = ' INSERT INTO ticketNumbers( ticketID, number ) VALUES( "'.$ticketID.'", "'.$value.'" ) '; $db->query($query); unset($randomTicketNumbers[$key]); if($addedNumberCount == $loopBreak){ break; }else{ $addedNumberCount++; } } $ticketCreationCount++; } But this isn't working it adds the right amount of tickets, which in the case for testing is 10,000 but then adds far too many ticket numbers, it ends up exceeding the million numbers in the random tickets array, The random tickets array is just a simple 1 tier array with 1 million numbers sorted randomly.

    Read the article

  • Cocos2d score resetting is messing up (long post warning)

    - by Jhon Doe
    The score is not resetting right at all,I am trying to make a high score counter where every time you passed previous high score it will update.However, right now it is resetting during the game. For example if I had high score of 2 during the game it will take 3 points just to put it up to 3 as high score instead of keep going up until it is game over. I have came to the conclusion that I need to reset it in gameoverlayer so it won't reset during game. I have been trying to to do this but no luck. hello world ./h #import "cocos2d.h" // HelloWorldLayer @interface HelloWorldLayer : CCLayer { int _score; int _oldScore; CCLabelTTF *_scoreLabel; } @property (nonatomic, assign) CCLabelTTF *scoreLabel; hello world init ./m _score = [[NSUserDefaults standardUserDefaults] integerForKey:@"score"]; _oldScore = -1; self.scoreLabel = [CCLabelTTF labelWithString:@"" dimensions:CGSizeMake(100, 50) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:32]; _scoreLabel.position = ccp(winSize.width - _scoreLabel.contentSize.width, _scoreLabel.contentSize.height); _scoreLabel.color = ccc3(255,0,0); [self addChild:_scoreLabel z:1]; hello world implement ./m - (void)update:(ccTime)dt { NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init]; CGRect projectileRect = CGRectMake( projectile.position.x - (projectile.contentSize.width/2), projectile.position.y - (projectile.contentSize.height/2), projectile.contentSize.width, projectile.contentSize.height); BOOL monsterHit = FALSE; NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init]; for (CCSprite *target in _targets) { CGRect targetRect = CGRectMake( target.position.x - (target.contentSize.width/2), target.position.y - (target.contentSize.height/2), target.contentSize.width, target.contentSize.height); if (CGRectIntersectsRect(projectileRect, targetRect)) { CCParticleFire* explosion = [[CCParticleFire alloc] initWithTotalParticles:200]; explosion.texture =[[CCTextureCache sharedTextureCache] addImage:@"sun.png"]; explosion.autoRemoveOnFinish = YES; explosion.startSize = 20.0f; explosion.speed = 70.0f; explosion.anchorPoint = ccp(0.5f,0.5f); explosion.position = target.position; explosion.duration = 1.0f; [self addChild:explosion z:11]; [explosion release]; monsterHit = TRUE; Monster *monster = (Monster *)target; monster.hp--; if (monster.hp <= 0) { [targetsToDelete addObject:target]; [[SimpleAudioEngine sharedEngine] playEffect:@"splash.wav"]; _score ++; } break; } } for (CCSprite *target in targetsToDelete) { [_targets removeObject:target]; [self removeChild:target cleanup:YES]; } if (targetsToDelete.count > 0) { [ projectilesToDelete addObject:projectile]; } [targetsToDelete release]; if (_score > _oldScore) { _oldScore = _score; [_scoreLabel setString:[NSString stringWithFormat:@"score%d", _score]]; [[NSUserDefaults standardUserDefaults] setInteger:_oldScore forKey:@"score"]; _score = 0; } } - (void)update:(ccTime)dt { NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init]; CGRect projectileRect = CGRectMake( projectile.position.x - (projectile.contentSize.width/2), projectile.position.y - (projectile.contentSize.height/2), projectile.contentSize.width, projectile.contentSize.height); BOOL monsterHit = FALSE; NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init]; for (CCSprite *target in _targets) { CGRect targetRect = CGRectMake( target.position.x - (target.contentSize.width/2), target.position.y - (target.contentSize.height/2), target.contentSize.width, target.contentSize.height); if (CGRectIntersectsRect(projectileRect, targetRect)) { CCParticleFire* explosion = [[CCParticleFire alloc] initWithTotalParticles:200]; explosion.texture =[[CCTextureCache sharedTextureCache] addImage:@"sun.png"]; explosion.autoRemoveOnFinish = YES; explosion.startSize = 20.0f; explosion.speed = 70.0f; explosion.anchorPoint = ccp(0.5f,0.5f); explosion.position = target.position; explosion.duration = 1.0f; [self addChild:explosion z:11]; [explosion release]; monsterHit = TRUE; Monster *monster = (Monster *)target; monster.hp--; if (monster.hp <= 0) { [targetsToDelete addObject:target]; [[SimpleAudioEngine sharedEngine] playEffect:@"splash.wav"]; _score ++; } break; } } for (CCSprite *target in targetsToDelete) { [_targets removeObject:target]; [self removeChild:target cleanup:YES]; } if (targetsToDelete.count > 0) { [projectilesToDelete addObject:projectile]; } [targetsToDelete release]; if (_score > _oldScore) { _oldScore = _score; [_scoreLabel setString:[NSString stringWithFormat:@"score%d", _score]]; [[NSUserDefaults standardUserDefaults] setInteger:_oldScore forKey:@"score"]; _score = 0; } The game overlayer .h file game over @interface GameOverLayer : CCLayerColor { CCLabelTTF *_label; CCSprite * background; int _score; int _oldScore; } @property (nonatomic, retain) CCLabelTTF *label; @end @interface GameOverScene : CCScene { GameOverLayer *_layer; } @property (nonatomic, retain) GameOverLayer *layer; @end .m file gameover #import "GameOverLayer.h" #import "HelloWorldLayer.h" #import "MainMenuScene.h" @implementation GameOverScene @synthesize layer = _layer; - (id)init { if ((self = [super init])) { self.layer = [GameOverLayer node]; [self addChild:_layer]; } return self; } - (void)dealloc { [_layer release]; _layer = nil; [super dealloc]; } @end @implementation GameOverLayer @synthesize label = _label; -(id) init { if( (self=[super initWithColor:ccc4(0,0,0,0)] )) { CGSize winSize = [[CCDirector sharedDirector] winSize]; self.label = [CCLabelTTF labelWithString:@"" fontName:@"Arial" fontSize:32]; _label.color = ccc3(225,0,0); _label.position = ccp(winSize.width/2, winSize.height/2); [self addChild:_label]; [self runAction:[CCSequence actions: [CCDelayTime actionWithDuration:3], [CCCallFunc actionWithTarget:self selector:@selector(gameOverDone)], nil]]; _score=0; }

    Read the article

  • Dropping not working on Chrome Mac version

    - by user600641
    I tried to work with html5 drag&drop api, and it works very well on my chrome 20.0.1132 on windows machine, but most fun - that the same version of chrome on mac os lion is not working. I mean dragstart is working, but drop event, dragleave, dragover is not fired. Here is html: <form id="fake_form" action="#" > <div id="canvas_wrapper" style="overflow: hidden;width: 600px; position: relative;border: 1px solid black; margin-left: 30px;"> <canvas width="600" height="300" > </canvas> </div> </form> Here is javascript: var canvas = $('canvas')[0]; canvas.addEventListener('dragenter', function(e){ console.log('dragenter'); }, false); canvas.addEventListener('dragleave', function(){ console.log('dragleave'); }, false) canvas.addEventListener('dragover', function(e){ console.log('dragover'); if(e.preventDefault){ e.preventDefault(); } return false; }, false); canvas.ondrop = function(e){ console.log('ondrop'); /** OTHER CODE **/ If it helps: on safari on the same mac - it works, i`m dragging image tags some of them have draggable attribute, some of them - not. Just checked - on canary mac version 22 it works. UPDATE: i figured out that there is some magic with dragstart event, if i delete line with this e.dataTransfer.setData('src', src_var) everythings become working

    Read the article

  • Custom Memory Allocator for STL map

    - by Prasoon Tiwari
    This question is about construction of instances of custom allocator during insertion into a std::map. Here is a custom allocator for std::map<int,int> along with a small program that uses it: #include <stddef.h> #include <stdio.h> #include <map> #include <typeinfo> class MyPool { public: void * GetNext() { return malloc(24); } void Free(void *ptr) { free(ptr); } }; template<typename T> class MyPoolAlloc { public: static MyPool *pMyPool; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; template<typename X> struct rebind { typedef MyPoolAlloc<X> other; }; MyPoolAlloc() throw() { printf("-------Alloc--CONSTRUCTOR--------%08x %32s\n", this, typeid(T).name()); } MyPoolAlloc(const MyPoolAlloc&) throw() { printf(" Copy Constructor ---------------%08x %32s\n", this, typeid(T).name()); } template<typename X> MyPoolAlloc(const MyPoolAlloc<X>&) throw() { printf(" Construct T Alloc from X Alloc--%08x %32s %32s\n", this, typeid(T).name(), typeid(X).name()); } ~MyPoolAlloc() throw() { printf(" Destructor ---------------------%08x %32s\n", this, typeid(T).name()); }; pointer address(reference __x) const { return &__x; } const_pointer address(const_reference __x) const { return &__x; } pointer allocate(size_type __n, const void * hint = 0) { if (__n != 1) perror("MyPoolAlloc::allocate: __n is not 1.\n"); if (NULL == pMyPool) { pMyPool = new MyPool(); printf("======>Creating a new pool object.\n"); } return reinterpret_cast<T*>(pMyPool->GetNext()); } //__p is not permitted to be a null pointer void deallocate(pointer __p, size_type __n) { pMyPool->Free(reinterpret_cast<void *>(__p)); } size_type max_size() const throw() { return size_t(-1) / sizeof(T); } void construct(pointer __p, const T& __val) { printf("+++++++ %08x %s.\n", __p, typeid(T).name()); ::new(__p) T(__val); } void destroy(pointer __p) { printf("-+-+-+- %08x.\n", __p); __p->~T(); } }; template<typename T> inline bool operator==(const MyPoolAlloc<T>&, const MyPoolAlloc<T>&) { return true; } template<typename T> inline bool operator!=(const MyPoolAlloc<T>&, const MyPoolAlloc<T>&) { return false; } template<typename T> MyPool* MyPoolAlloc<T>::pMyPool = NULL; int main(int argc, char *argv[]) { std::map<int, int, std::less<int>, MyPoolAlloc<std::pair<const int,int> > > m; //random insertions in the map m.insert(std::pair<int,int>(1,2)); m[5] = 7; m[8] = 11; printf("======>End of map insertions.\n"); return 0; } Here is the output of this program: -------Alloc--CONSTRUCTOR--------bffcdaa6 St4pairIKiiE Construct T Alloc from X Alloc--bffcda77 St13_Rb_tree_nodeISt4pairIKiiEE St4pairIKiiE Copy Constructor ---------------bffcdad8 St13_Rb_tree_nodeISt4pairIKiiEE Destructor ---------------------bffcda77 St13_Rb_tree_nodeISt4pairIKiiEE Destructor ---------------------bffcdaa6 St4pairIKiiE ======Creating a new pool object. Construct T Alloc from X Alloc--bffcd9df St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d028 St4pairIKiiE. Destructor ---------------------bffcd9df St4pairIKiiE Construct T Alloc from X Alloc--bffcd95f St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d048 St4pairIKiiE. Destructor ---------------------bffcd95f St4pairIKiiE Construct T Alloc from X Alloc--bffcd95f St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d068 St4pairIKiiE. Destructor ---------------------bffcd95f St4pairIKiiE ======End of map insertions. Construct T Alloc from X Alloc--bffcda23 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d068. Destructor ---------------------bffcda23 St4pairIKiiE Construct T Alloc from X Alloc--bffcda43 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d048. Destructor ---------------------bffcda43 St4pairIKiiE Construct T Alloc from X Alloc--bffcda43 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d028. Destructor ---------------------bffcda43 St4pairIKiiE Destructor ---------------------bffcdad8 St13_Rb_tree_nodeISt4pairIKiiEE Last two columns of the output show that an allocator for std::pair<const int, int> is constructed everytime there is a insertion into the map. Why is this necessary? Is there a way to suppress this? Thanks! Edit: This code tested on x86 machine with g++ version 4.1.2. If you wish to run it on a 64-bit machine, you'll have to change at least the line return malloc(24). Changing to return malloc(48) should work.

    Read the article

  • creating a wordpress dev enviornment and uploading to production

    - by Jeff
    I am an old school java developer who is considering a using wordpress. I'm used to developing locally on my PC (yeah yeah not even a mac) and then ftping my files up to a production environment on a remote server. My high level review of wordpress gives me the impression that typically there is no concept of lower environments and that all updates occur directly in production. Is this the case? If not, can someone explain how one goes about uploading the files to a web site? Thanks, Jeff

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >