I'm doing a method which creates you a custom sprite with a platform image and many invisible boxes to do the physic body . In this method I make three principal objects: the sprite image (platform), two "walls" with physics bodies (one at the top left and one at the top right of the sprite) and the ground which are boxes that goes along the ground between the walls.
I want to focus the single line of code which is making troubles.
As you can see in the image, I'm getting a result of 0.600000024 allways, whatever the value of "totalCajas" is. In this case the variable "totalCajas" is equal to 10 and the minaPek.size.width value is always 300 in this case so normally
(minaPek.size.width/500 == 0.6) - (10/100 == 0.1) should be equal to 0.5
So I don't understand why I'm getting this error. Any help would be apreciated!!
Let me explain you two simple things about the method, the param pos (position) are degrees and it's exactly like the x position of the sprite.
The param distMoon is the y position. It's actually the radius.
Size obviously is the size of the sprite. Thank you very much in advance for learnCocos2D cause he is always faster.
-(void)plataformaCustom:(CGFloat)pos Altura:(CGFloat)distMoon size:(CGSize)Size
{
XYZCajas *minaPek = [[XYZCajas alloc]crearMinaMed];
[minaPek setSize:Size];
[minaPek setDistanciaLuna:distMoon];
[self.world addChild:minaPek];
NSArray *temp = [NSArray arrayWithObjects:minaPek, nil];
[objetosMovimiento addObjectsFromArray:temp];
[superCaja setObjectsMovimiento:objetosMovimiento];
//A CONTINUACION creo un int con el numero total de cajas. Me servirá para posteriormente posicionarlas en los extremos/saber cuantos grados tienen
int totalCajas = minaPek.size.width / 20;
//A CONTINUACION Creo un bool que me hará saber cuando tengo colocada la pared izquierda
bool paredIzquierda = NO;
bool paredDerecha = NO;
for (totalCajas; totalCajas >=0; totalCajas--)
{
//APUNTE Cada 100 de ancho de la mina = 0.2 grados de distancia de la pared
// la distancia entre caja y caja es de 0.1
//A CONTINUACION
//coloco la pared izquierda.
if (paredIzquierda == NO)
{
XYZCajas *paredIzq =[[XYZCajas alloc]crearParedSinImagen];
[paredIzq setGrados:-1*(minaPek.size.width/500)];
[paredIzq setDistanciaLuna:distMoon+5];
[paredIzq setName:#"paredIzqPrueba"];
[self.world addChild:paredIzq];
NSArray *temp2 = [NSArray arrayWithObjects:paredIzq, nil];
[objetosCajas addObjectsFromArray:temp2];
[superCaja setObjects:objetosCajas];
paredIzquierda = YES;
totalCajas --;
}
//A CONTINUACION
//coloco la pared derecha
if (paredDerecha == NO)
{
XYZCajas *paredDer =[[XYZCajas alloc]crearParedSinImagen];
[paredDer setGrados:minaPek.size.width/500];
[paredDer setDistanciaLuna:distMoon+5];
[self.world addChild:paredDer];
NSArray *temp2 = [NSArray arrayWithObjects:paredDer, nil];
[objetosCajas addObjectsFromArray:temp2];
[superCaja setObjects:objetosCajas];
paredDerecha = YES;
totalCajas --;
}
//A CONTINUACION
//creamos cajas
XYZCajas *caja22 =[[XYZCajas alloc]crearCajaSinImagen];
float gradosCaja = ((minaPek.size.width/500) - (totalCajas/100));
[caja22 setGrados:gradosCaja];
[caja22 setDistanciaLuna:distMoon+20];
[self.world addChild:caja22];
NSArray *temp2 = [NSArray arrayWithObjects:caja22, nil];
[objetosCajas addObjectsFromArray:temp2];
[superCaja setObjects:objetosCajas];
}
Related
I got a sheet with merged cells and in those merged cells, a script write its results.
When I copy this result in the merged cells, it gave me multiple spaces at the end.
Like : Result #1________ (« _ » represent invisible space)
When I put the same result in a normal cell (not merged), it doesn’t put any space at the end.
Result #1
I tried multiple cell format (Center aligned, left aligned, etc.) but nothing changed.
Do you have any idea why ?
Thanks !
EDIT : add script
Script
function Devise() {
const sheetName = "Missions";
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var Devise = "";
var NombreMission = "";
var NomOperateurs = "";
if(sheet.getRange("H2").getValue()=="") { // Si la mission 7 est vide
NombreMission = 6; // On compte seulement 6 missions
} else {
NombreMission = 7; // Sinon on compte 7 missions
}
for (i = 1; i < NombreMission+1; i++) { // Boucle FOR pour NombreMission missions
if(sheet.getRange(2,i+1).getValue()=="") { continue; } // Si la mission est vide, on la passe
Devise = Devise + i + "/";
l = 0; // Variable pour indiquer "Rien" si personne à placer dans la mission
NomOperateurs = ""; // Reset les noms pour la mission d'après
for (j = 1; j < 27+1; j++) { // Boucle FOR pour tous les opérateurs
if(sheet.getRange(j+2,i+1).getFontWeight() == 'bold') { // Vérifie si la case est en gras
/*if(i!=NombreMission) { // Tant qu'il ne s'agit pas de la dernière mission ...
Devise = Devise + sheet.getRange(j+2,1).getValue() + " "; // ... on affiche les opérateurs
}*/
NomOperateurs = NomOperateurs + sheet.getRange(j+2,1).getValue() + " ";
l = l + 1; // On compte les opérateurs
}
} // Fin Boucle FOR opérateurs
if (l==24) { // S'il y a tous les operateurs sur une mission...
Devise = Devise + "ALL OPs! " // ... On affiche "All Op!"
} else if (i==NombreMission && l!=0) { // Sinon s'il s'agit de la dernière mission et qu'il reste des opérateurs à placer...
Devise = Devise + "Autres + Epic "; // ... On indique qu'il s'agit du reste et des épiques
} else if (l==0) { // Sinon s'il n'y a aucun opérateurs à placer...
Devise = Devise + "RIEN " // ... On indique "RIEN"
} else { // Sinon ...
Devise = Devise + NomOperateurs; // ... On affiche les opérateurs
}
} // FIN BOUCLE FOR NombreMission
if(NombreMission==6 && Devise!="") { Devise = Devise + "7/!NOTHING!";}
sheet.getRange("K13").setValue(Devise);
}
Your problem is related to the data you copied and the way that you copied it as pasting text in merged cells doesn't create any new lines.
Also, an important thing to keep in mind is that CTRL+ENTER creates the mentioned space also known as a line break.
So, for example, if this cell contains the text Text + line break:
And the text from the above cell is copied and pasted into a merged cell it will look like this - which is the same outcome as the one that you have mentioned:
But if you paste the same text to a simple cell, it will look like this:
This is essentially because the line break will signify the start of a new cell.
For example, this cell contains this text with line breaks:
After the text is copied and pasted into a different cell, this is how it will actually be pasted as:
In order to solve your issue, I suggest you to copy only the text needed and if possible to avoid using any line breaks.
Reference
Edit and Format a Spreadsheet.
Encountering the same issue.
I have a merged cell with text. If I select the cell and paste it into notepad, It includes quite a lot of white space.
I've checked and if the merged cell spans two rows, the white space includes a line break.
If the merged cell spans one row but two columns, the white space does not include a line break.
If I have a single cell and have it take its value from the mered cell "=A1", the text does not include the white space.
So the addition of the whitespace is definitely the result of having a merged cell.
I have a function which does some array manipulation on an NSMutableArray. Somehow after a couple of loops of the while function the values inside 2 local variables are total garbage. They are not being assigned or manipulated anywhere. Here's how:
Here's the function:
-(void) normalize_path:(NSMutableArray *)path tool:(Tool)tool
{
NSUInteger last_accepted_point_index = 0;
NSUInteger current_point_index = 1;
while(current_point_index < [path count]){
VPoint * p1, * p2;
[[path objectAtIndex:last_accepted_point_index] getValue:&p1];
[[path objectAtIndex:current_point_index] getValue:&p2];
//float distance = [self distance_between:p1 and:p2];
// if(distance < MIN_POINT_DISTANCE){
// [path removeObjectAtIndex:current_point_index];
// }else{
// float opacity = tool.max_opacity - distance * tool.opacity_sensitivity;
// opacity = opacity <= tool.min_opacity ? tool.min_opacity : opacity;
// p2->opacity = opacity;
// float thickness = tool.max_thickness - distance * tool.thickness_sensitivity;
// thickness = thickness <= tool.min_thickness ? tool.min_thickness : thickness;
// p2->thickness = thickness;
// last_accepted_point_index = current_point_index;
// //current_point_index++;
// }
}
}
And it's called only in one place like so:
//...
[self normalize_path:opath tool:pen];
//...
Every run creates different values. I am confounded! What is going on here?
I think that this may be a memory issue which you can fix by removing the & from in front of p1 and p2 in the getValue: call. It's difficult to be totally sure as you haven't said what VPoint is, but normally this code would look like this:
VPoint p1, p2;
[[path objectAtIndex:last_accepted_point_index] getValue:&p1];
[[path objectAtIndex:current_point_index] getValue:&p2];
This would then set p1 and p2 to the actual values. Your distance between function would then not take references but the actual values of p1 and p2 (if you want to pass references as you are doing now, you'd put & in front of p1 and p2 in the distance callBetween method call.
I am currently making a Flappy Bird-copy. Relax, its just for me and the learningpart, im not going to publish it, so dont hate.
The bird is locked at:
self.size.width/3
The pipes are generated like this:
- (void)generatePipes {
for (NSInteger i = 0; i < 3; i++) {
pipeNode = [SKNode node];
[pipeNode setName:#"pipe"];
[pipeNode setPosition:CGPointMake(self.size.width + 100.0 + (200.0 * i), 0.0)];
[self addChild:pipeNode];
**BLABLABLA. Some code**
[pipeTop setPosition:CGPointMake(0.0, arc4random_uniform(250) + 460.0)];
[pipeBottom setPosition:CGPointMake(0.0, pipeTop.position.y - (550.0 + arc4random_uniform(10)))];
[pipeTop setPhysicsBody:[SKPhysicsBody bodyWithRectangleOfSize:pipeTop.size]];
[pipeBottom setPhysicsBody:[SKPhysicsBody bodyWithRectangleOfSize:pipeBottom.size]];
[pipeTop.physicsBody setDynamic:NO];
[pipeBottom.physicsBody setDynamic:NO];
pipeTop.physicsBody.categoryBitMask = blockBitMask;
pipeBottom.physicsBody.categoryBitMask = blockBitMask;
pipeNode.physicsBody.categoryBitMask = blockBitMask;
[pipeNode addChild:pipeTop];
//[pipeTop attachDebugRectWithSize:pipeTop.size];
//[pipeBottom attachDebugRectWithSize:pipeBottom.size];
[pipeNode addChild:pipeBottom];
}
}
THis is the only thing i have made somewhat work, and yes, i am new to game-development. FirstDistance is the distance before the first pipe arrive:
firstDistance += -moveAmount.x;
if(touchBegan > 0 && firstDistance > (self.size.width -(self.size.width/3)- 60)){
distanceSinceLastPipe += -moveAmount.x;
if (distanceSinceLastPipe >= 140.0) {
distanceSinceLastPipe = 0.0;
score += 1;
[_scoreLabel setText:[NSNumberFormatter localizedStringFromNumber:#(score)
numberStyle:NSNumberFormatterDecimalStyle]];
[self runAction:[SKAction playSoundFileNamed:#"pipe.mp3" waitForCompletion:NO]];
}
}
How do i tell the update-method that the pipes are passing the bird most efficent? Count pixels between pipes and reset it? Or is it any way to detect when they pass?
If you know the horizontal position of the bird you could use some "simple" math to calculate how long it will take the pipe to reach the position that means it has passed the bird. Some pseudoCode:
CGFloat totalDistanceForPipeToMove = pipe.position.x - endPosition.x; // endPosition == the final destination for the pipe.
CGFloat relativeSpeed = totalDistanceForPipeToMove / duration; // duration being the SKAction's duration
CGFloat distanceToBird = pipe.position.x - birdPosition.x;
CGFloat timeThePipeReachesTheBird = distanceToBird / relativeSpeed;
Then you can create an SKActionSequence, firing it at the same time as the pipe begins to move:
SKAction *wait = [SKAction waitForDuration: timeThePipeReachesTheBird];
SKAction *addToScore = [SKAction performSelector:#selector(addToScore) onTarget:self]; // performing the addToScore method
SKAction *sequence = [SKAction sequence:#[wait, addToScore]];
Another way to achieve what you are looking for is by having an invincible sprite trailing the birdSprite. Whenever this "scoreSprite" collides with a pipe you know the pipe has passed the bird...
i'm trying to reorder a table view - have set up the canMoveRowAtIndexPath and moveRowAtIndexPath so that I can drag the cells around when i'm in editing mode, but I need to basically mirror these changes in an sqlite database that I have. i have a column called "orderid" which i'm using to keep track of the order of the cells. My approach has been to basically set the cell being moved to orderid=9999, then add or subtract 1 from from the orderid of the rest of the affected cells, then set the new cell to its destination orderid. i think it's likely to be an sql error but i can't figure it out. if anyone has any advice it would be much appreciated.
these are my methods:
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
long source = (long)sourceIndexPath.row;
long dest = (long)destinationIndexPath.row;
source++;
dest++;
//reorder in db
NSString *sql;
if (source>dest) {
sql = [NSString stringWithFormat:#"UPDATE entries SET orderid=9999 where orderid=%ld; update entries set orderid = orderid + 1 where orderid<%ld AND orderid>=%ld update entries set orderid=%ld where orderid=9999", source, source,dest, dest];
} else if (source<dest){
sql = [NSString stringWithFormat:#"UPDATE entries SET orderid=9999 where orderid=%ld; update entries set orderid = orderid - 1 where orderid BETWEEN orderid>%ld AND orderid<=%ld; update entries set orderid=%ld where orderid=9999", source, source, dest, dest];
}
NSLog(#"%#", sql);
char *err;
if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) !=SQLITE_OK) {
sqlite3_close(db);
NSLog(#"could not reorder");
} else {
NSLog(#"rows reordered");
}
}
I am using pageOrder to create an order in my pages table. This is table :
.s pages
CREATE TABLE pages (
uuid INTEGER PRIMARY KEY,
name TEXT,
pageOrder INTEGER DEFAULT 0
);
Here is the code :
int fromRow = [sourceIndexPath row];
int toRow = [destinationIndexPath row];
if (toRow != fromRow) {
FMDatabase* db = [FMDatabase databaseWithPath:[appDelegate dbPath]];
[db open];
[db executeUpdate:#"UPDATE pages SET pageOrder = -? WHERE pageOrder = ?",
[NSNumber numberWithInt:toRow + 1],
[NSNumber numberWithInt:fromRow + 1]];
if (toRow < fromRow) {
[db executeUpdate:#"UPDATE pages SET pageOrder = pageOrder + 1 WHERE pageOrder > ? AND pageOrder <= ?",
[NSNumber numberWithInt:toRow],
[NSNumber numberWithInt:fromRow]];
} else {
[db executeUpdate:#"UPDATE pages SET pageOrder = pageOrder - 1 WHERE pageOrder > ? AND pageOrder <= ?",
[NSNumber numberWithInt:fromRow],
[NSNumber numberWithInt:toRow + 1]];
}
[db executeUpdate:#"UPDATE pages SET pageOrder = abs(pageOrder) WHERE pageOrder < 0"];
[db close];
}
Should be working,
Cheers,
Eddy
One possibility may be if the numberOfRows in your tableView does not match the number of entries in your database, for example: if you have an ‘Add new row...’ cell on the bottom of the tableView, then you may run into trouble, like I have in the past. My trouble was that the tableView:moveRowAtIndexPath:toIndexPath was returning the wrong sourceIndexPath. Two solutions both solved the problem. First solution: Call [tableview reloadData] in the tableView:moveRowAtIndexPath:toIndexPath:, you may lose the row animation but you will keep the functionality and sourceIndexPath/destinationIndexPath will be updated. Second solution: Don’t use an ‘Add new row...’ cell on the bottom and find alternate solution to add. Good luck!
I would suggest using float order_id. And when user reorders item, get order_id of previous and next item, get their mean (float) and save to DB. This way, you need to update only reordered item.
This Works fine with me!
- (void) tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)targetIndexPath{
// Define las variables a utilizar: IDorigen hace referencia al ID que tiene la fila antes de moverse e IDDestino hace referencia al ID que va a tener la fila luego de moverse
int IDorigen = (int)[sourceIndexPath row]+1;
int IDdestino = (int)[targetIndexPath row]+1;
int diferencia;
// Define la variable de consulta sobre la base de datos
NSString *consulta;
// Si el IDorigen es menor al IDdestino (es decir, mueve una fila hacia abajo)
if (IDorigen < IDdestino)
{
// Obtiene la diferencia para saber cuantas filas hay entre IDdestino e IDOrigen
diferencia = IDdestino - IDorigen;
// Hace un FOR desde cero hasta diferencia, y a cada fila que encuentra le pone el ID=9000+i. Esto se hace para mandar las filas invoulucradas en el movimientohacia abajo de todo y evitar conflictos de ID
for (int i=0;i<diferencia;i++){
// Define la consulta
consulta = [NSString stringWithFormat:#"update homeTabla set ID=%d where ID=%d", 9000+i,IDorigen+1+i];
// Ejecuta la consulta
[self.dbTouchMeCIS executeQuery:consulta];
}
// Cuando finaliza el FOR, le asigna a la fila que se está moviendo, el IDdestino deseado definiendo la consulta
consulta = [NSString stringWithFormat:#"update homeTabla set ID=%d where ID=%d", IDdestino,IDorigen];
// Ejecuta la consulta
[self.dbTouchMeCIS executeQuery:consulta];
// Hace un FOR para asignarle el valor que corresponde a aquellas filas que se le asigno el ID=9000+i
for (int i=0;i<diferencia;i++){
// Define la consulta
consulta = [NSString stringWithFormat:#"update homeTabla set ID=%d where ID=%d",IDorigen+i,9000+i];
// Ejecuta la consulta
[self.dbTouchMeCIS executeQuery:consulta];
}
// Si el IDorigen es mayor al IDdestino (es decir, mueve una fila hacia arriba)
}else if (IDorigen > IDdestino){
// Obtiene la diferencia para saber cuantas filas hay entre IDdestino e IDOrigen
diferencia = IDorigen - IDdestino;
// Hace un FOR desde cero hasta diferencia, y a cada fila que encuentra le pone el ID=9000+i. Esto se hace para mandar las filas involucradas en el movimiento hacia abajo de todo y evitar conflictos de ID
for (int i=0;i<diferencia;i++){
// Define la consulta
consulta = [NSString stringWithFormat:#"update homeTabla set ID=%d where ID=%d", 9000+i,IDdestino+i];
// Ejecuta la consulta
[self.dbTouchMeCIS executeQuery:consulta];
}
// Cuando finaliza el FOR, le asigna a la fila que se está moviendo, el IDdestino deseado definiendo la consulta
consulta = [NSString stringWithFormat:#"update homeTabla set ID=%d where ID=%d", IDdestino,IDorigen];
// Ejecuta la consulta
[self.dbTouchMeCIS executeQuery:consulta];
// Hace un FOR para asignarle el valor que corresponde a aquellas filas que se le asigno el ID=9000+i
for (int i=0;i<diferencia;i++){
// Define la consulta
consulta = [NSString stringWithFormat:#"update homeTabla set ID=%d where ID=%d",IDdestino+1+i,9000+i];
// Ejecuta la consulta
[self.dbTouchMeCIS executeQuery:consulta];
}
}
// Recarga la base de datos en la tabla una vez finalizado el movimiento
[self recargarDatos];
}
following image is showing the negative life of the player.... because intersecting with obstacles in the way...i want the solution for only decreasing life by one point after intersecting.
if (Texture.playerrect.Intersects(Texture.mirchirect) || Texture.playerrect.Intersects(Texture.crabrect) || Texture.playerrect.Intersects(Texture.stonerect) || Texture.playerrect.Intersects(Texture.cactusrect))
{
die = true;
currentframe = 19;
}
else { die = false; }
if (die)
{
life -= 1;
}
Maybe it's because the code is updating 60 frames per second and die == true, then the life of your object would decrease by 60 each second, instead of 1.
possible way... add one bollean variable PlayerHitted to your obstacles, and when collision happened set life -= 1 if PlayerHitted is false (by default) and update PlayerHitted to true.
that way obstacles will have information if they hit player
if (Texture.playerrect.Intersects(Texture.mirchirect) || Texture.playerrect.Intersects(Texture.crabrect) || Texture.playerrect.Intersects(Texture.stonerect) || Texture.playerrect.Intersects(Texture.cactusrect))
{
die = true;
currentframe = 19;
if (!Update)
{
life--;
Update = true;
}
}
else { die = false; Update = false; }