I want to create an object at a position where there is nothing, but there is something wrong - visual-studio

I'm making a game in Unity2D where are 4 roads that tanks drive on, tanks spawn in random positions, I want to make sure that a tank can't spawn in a position that another tank is already in. When I start the game the Unity Editor crashes I think there is a problem somewhere in the do while loop but I haven't found it, hoping I described it right.
Thanks.
{
public GameObject tank;
public float spawnTime = 1f;
float positionX;
float positionY;
private bool check;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("TankSpawn", 1f, spawnTime);
}
void TankSpawn()
{
do
{
int rndY = Random.Range(1, 5);
float rndX = Random.Range(20.5f, 35.0f);
if (rndY == 1)
{
positionY = -3.5f;
positionX = rndX;
}
else if (rndY == 2)
{
positionY = 0.5f;
positionX = rndX;
}
else if (rndY == 3)
{
positionY = 4.5f;
positionX = rndX;
}
else if (rndY == 4)
{
positionY = 8.5f;
positionX = rndX;
}
GameObject[] tanks = GameObject.FindGameObjectsWithTag("tank");
foreach (GameObject tank in tanks)
{
if (tank.transform.position.x == positionX && tank.transform.position.y == positionY)
{
check = false;
}
else
{
check = true;
}
}
} while (check != true);
Instantiate(tank, new Vector2(positionX, positionY), transform.rotation);
}
}```

Firstly the problem that is doing you in:
By default bool variables. like check, are false. The while loops when check is false. The only way for check to be set to true is thru the forloop if the generated coordinates don't match any tank positions. The problem with that is that if there are no tanks in the scene the forloop is never even started meaning that there is no way for check to become true, ergo your while loop keeps looping and hangs up your editor.
A quick solution would be to check the length of found tanks array and if it is zero set check to true.
if (tanks.Length == 0)
{
check = true;
}
Sidenotes:
There is name ambiguity between the tank in the forloop and the tank in the prefab. Its good practice to avoid that.
It is extremely hard to match two float values with == due to rounding. They might be extremely close, but are still different.
With your method tanks will still overlap. I would recommend to check if a position is truly free, by using Physics2D.OverlapBox or Physics2D.OverlapCircle
If a lot of tanks spawn there might not be any valid positions. You should think of a way to timeout or impose some other limit, else you'll get softlocked in the while loop again.

Related

Unity c# having trouble getting it too detect when a key is not pressed

if (Input.GetKeyDown("z") == true)
{
moveSpeed = 10;
}
else if (Input.GetKeyDown("z") == false)
{
moveSpeed = 5;
}
that is the code.
When it runs it seems to detect that z is pressed and than set moveSpeed to 10. But than it fails to detect that z is not pressed and resets moveSpeed back to 5.
I have tried a few variations of this code, all seem to have the same result.
you must use Input.GetKeyUp("z")

p5.play counter not working

I'm trying to write a program in which the end screen of the game only shows up after the last animation finishes. I'm using a counter that's implemented after each object is removed (which is only after it finishes its animation), and when that counter gets to zero, it should show the end screen. Unfortunately, from what I can tell, the counter statement isn't registering at all. I've inserted a print statement that isn't functioning.
var star;
var score;
var counter;
function setup() {
createCanvas(600,400);
score = 0;
counter = 20;
for (var s = 0; s < 20; s++) {
star = createSprite(random(width), random(height));
star.addAnimation("idle", idleAnim);
star.addAnimation("explode", explAnim);
star.changeAnimation("idle");
star.onMousePressed = function() {
this.changeAnimation("explode");
this.animation.looping = false;
score +=1
if (this.getAnimationLabel() == "explode" && this.animation.getFrame() == this.animation.getLastFrame()) {
this.remove();
counter -= 1;
print(counter);
}
}
}
}
function draw() {
if (score == 20 && counter == 0) {
background(255,222,51)
textSize(90);
fill(0)
text("YOU WIN!",95,225)
} else {
drawSprites();
}
}
You need to take a step back and debug your program. For example, are you sure the star.onMousePressed() function is firing? Are you sure the if statement is working the way you expected? Are you sure the player.dir() function is being called?
It sounds like your if statement is not being entered. can you find out the value of everything on that line? Which thing has a different value from what you expected?
Use console.log() statements, or use the JavaScript debugger, to answer all of the above. Figure out exactly which line of code is behaving differently from what you expected, and then isolate that problem in a MCVE. Good luck.

Making a game with 4 possible answer buttons

I am new to ActionScript-3 and I am attempting to make a game to learn more.
For every picture that is displayed I want there to be 4 choices (buttons) and only one of them to be the correct one. But how can I make it so that the text from the buttons will be random.
As you can see I've made it so the 4th button is always the correct answer. I don't want to make all this thing for every picture that is displayed...to much pointless code.
Can anybody help me? If you need extra information I will gladly provide it.
var k:int;
for(k=1;k<=3;k++)
{
GAME.variante.buttonMode=true;
GAME.variante.addEventListener(MouseEvent.MOUSE_OVER,mouse_over_variante);
GAME.variante.addEventListener(MouseEvent.MOUSE_OUT,mouse_out_variante);
GAME.variante.varianta_corecta.addEventListener(MouseEvent.CLICK,variante);
GAME.variante.varianta_gresita1.addEventListener(MouseEvent.CLICK,variante_gresiteunu);
GAME.variante.varianta_gresita2.addEventListener(MouseEvent.CLICK,variante_gresitedoi);
GAME.variante.varianta_gresita3.addEventListener(MouseEvent.CLICK,variante_gresitetrei);
GAME.varianta1.text = "Cameleon";
GAME.varianta2.text = "Snake";
GAME.varianta3.text = "Frog";
GAME.varianta4.text = "Snail";
function variante_gresiteunu(e:MouseEvent){
if (varianta_gresita_apasata1 == 1){
totalScore -= score_variante_gresite;
GAME.text1.text = totalScore;
varianta_gresita_apasata1 = 2;
}
}
function variante_gresitedoi(e:MouseEvent){
if (varianta_gresita_apasata2 == 1){
totalScore -= score_variante_gresite;
GAME.text1.text = totalScore;
varianta_gresita_apasata2 = 2;
}
}
function variante_gresitetrei(e:MouseEvent){
if (varianta_gresita_apasata3 == 1){
totalScore -= score_variante_gresite;
GAME.text1.text = totalScore;
varianta_gresita_apasata3 = 2;
}
}
}
GAME.extra_points.visible = false;
function variante (e:MouseEvent) {
if (GAME.stichere.sticker1.currentFrame == (1)){
GAME.extra_points.visible = true;
GAME.extra_points.plus_ten1.gotoAndPlay(1);
}
//go to great job screen
GAME.greatJob.stars.gotoAndPlay(1);
GAME.greatJob.visible = true;
}
function mouse_over_variante (e:MouseEvent) {
trace(e.target.name);
e.target.gotoAndPlay(1);
}
function mouse_out_variante (e:MouseEvent) {
e.target.gotoAndStop(1);
}
You like to have 4 images and they will be tested right?
The text below the images will be randomness. I saw your code and I
confess I was confused. I made a different one.
I undestand that this code is a little diferent of what you ask, but i think it will > give you some new ideas and help you on your app...
//start button added on the sceen named f3toc. I give a function name for him f3roll.
f3toc.addEventListener(MouseEvent.CLICK,f3roll);
function f3roll(e:MouseEvent):void{
//creating variables for the picture.
var bola:Number
var quadrado:Number
var pentagono:Number
//Here is just a randomization code, you can change it to the what you want to use after the =
bola = Math.ceil(Math.random() * 10);
pentagono = Math.ceil(Math.random() * 10);
f3res1_txt.text = String (bola + 8 + 8);
f3res2_txt.text = String(bola - 1 + bola);
f3res3_txt.text = String (pentagono + 10 - bola);
//converting number to string so we can put tem into the text fields.
var pentagonotring:String = pentagono.toString();
var bolastring:String = bola.toString();
//function to check wen the name is correct. each wrong do nothing and every correct add 1 to a variable, in the end wen this variable reach 3 it does something.
f3check_bnt.addEventListener (MouseEvent.CLICK, f3check);
function f3check (e:MouseEvent):void{
if (f3inp2_txt.text == pentagonotring){
f3ver_ext2.text = "Correct"
} else {f3ver_ext2.text = "Wrong";}
if (f3inp1_txt.text == bolastring){
f3ver_ext1.text = "Correct"
}else {f3ver_ext1.text = "Wrong";}
// function to check wen the variable pass reach 3
pass = 0;
if (f3ver_ext1.text == "Correct"){
pass++
}
if (f3ver_ext2.text == "Correct"){
pass++
if (pass == 3){
nextFrame();
}}}}

how to set "smart" breakpoint in Xcode when method returns a specific value?

I have a method which returns a bool value, with several exit points.
However, it does not seem to work correctly, so I would like to set an automatic breakpoint to see when it returns a YES value, so I can check all the variables and calculations in the debugger.
I would like to stop the debugger whenever a YES value is returned.
I have a similar smart breakpoint set for objc_exception_throw, so I know it's possible, I am just not sure how.
(In case it helps anyone, the way you can set the exception breakpoint: in the Breakpoints window (Run -> Show -> Breakpoints) enter objc_exception_throw as "Breakpoint", and libobjc.A.dylib as "Location")
EDIT: the specific code I would like to use it for:
- (BOOL)collisionOccured {
// Assumption: helicopter is of square shape (collision calculated by radius), walls are rectangles
// This approach is based on the solution seen here: http://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection/402010#402010
float helicopterImageWidth = [helicopter texture].contentSize.width;
float wallImageWidth = [[walls lastObject] texture].contentSize.width;
float wallImageHeight = [[walls lastObject] texture].contentSize.height;
float helicopterCollisionRadius = helicopterImageWidth * 0.4f;
CGPoint helicopterPosition = helicopter.position;
int numWalls = [walls count];
for (int i = 0; i < numWalls; i++) {
CCSprite *wall = [walls objectAtIndex:i];
if ([wall numberOfRunningActions] == 0) {
// The wall is not moving, we can skip checking it.
continue;
}
CGPoint wallPosition = wall.position;
float helicopterDistanceX = abs(helicopterPosition.x - wallPosition.x - wallImageWidth/2);
float helicopterDistanceY = abs(helicopterPosition.y - wallPosition.y - wallImageHeight/2);
if (helicopterDistanceX > (wallImageWidth/2 + helicopterCollisionRadius)) { return NO; }
if (helicopterDistanceY > (wallImageHeight/2 + helicopterCollisionRadius)) { return NO; }
if (helicopterDistanceX <= (wallImageWidth/2)) { return YES; }
if (helicopterDistanceY <= (wallImageHeight/2)) { return YES; }
float cornerDistance_sq = powf((helicopterDistanceX - wallImageWidth/2), 2) +
powf((helicopterDistanceY - wallImageHeight/2), 2);
return (cornerDistance_sq <= powf(helicopterCollisionRadius, 2));
}
// this should not occur
return NO;
}
This method is called via
- (void)update:(ccTime)delta {
if ([self collisionOccured]) {
NSLog(#"A collision occured");
}
}
The problem is that the update method takes delta (time passed) as argument, so I can't check what's happening frame by frame -- whenever I continue the execution, I am presented with a different scene.
(I am using cocos2d in the code)
You can set conditional breakpoints. With a slight tweak to update:
- (void)update:(ccTime)delta {
BOOL collided = [self collisionOccured];
if (collided) {
NSLog(#"A collision occured");
}
}
you can set a breakpoint as normal after the BOOL's assignment (i.e. on the if line), then right-click on the blue breakpoint arrow and select "Show Message Bubble", and add collided as the Condition. The extra variable should get optimized away in Release build mode.
If you're using a local return variable:
- (BOOL)someMethod {
BOOL ret = NO;
if (something) {
ret = YES;
} else if (something_else) {
ret = YES;
}
// ... and so on
return ret;
}
You can just set a watch point on ret
Otherwise, you're probably stuck with stepping through the code—hopefully some clever combination of conditional breakpoints will help you not have to break on every invocation. Setting a method breakpoint like you do with objc_exception_throw wouldn't work, because it will stop on every invocation, and breaking on the return value at the calling site is too late to figure out how you got there.
If you can post the code, we may be able to give more specific help as to a debugging strategy. Good luck. :-)

Redundant code constructs

The most egregiously redundant code construct I often see involves using the code sequence
if (condition)
return true;
else
return false;
instead of simply writing
return (condition);
I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java. What other such constructs would you flag in a code review?
if (foo == true)
{
do stuff
}
I keep telling the developer that does that that it should be
if ((foo == true) == true)
{
do stuff
}
but he hasn't gotten the hint yet.
if (condition == true)
{
...
}
instead of
if (condition)
{
...
}
Edit:
or even worse and turning around the conditional test:
if (condition == false)
{
...
}
which is easily read as
if (condition) then ...
Using comments instead of source control:
-Commenting out or renaming functions instead of deleting them and trusting that source control can get them back for you if needed.
-Adding comments like "RWF Change" instead of just making the change and letting source control assign the blame.
Somewhere I’ve spotted this thing, which I find to be the pinnacle of boolean redundancy:
return (test == 1)? ((test == 0) ? 0 : 1) : ((test == 0) ? 0 : 1);
:-)
Redundant code is not in itself an error. But if you're really trying to save every character
return (condition);
is redundant too. You can write:
return condition;
Declaring separately from assignment in languages other than C:
int foo;
foo = GetFoo();
Returning uselessly at the end:
// stuff
return;
}
I once had a guy who repeatedly did this:
bool a;
bool b;
...
if (a == true)
b = true;
else
b = false;
void myfunction() {
if(condition) {
// Do some stuff
if(othercond) {
// Do more stuff
}
}
}
instead of
void myfunction() {
if(!condition)
return;
// Do some stuff
if(!othercond)
return;
// Do more stuff
}
Using .tostring on a string
Putting an exit statement as first statement in a function to disable the execution of that function, instead of one of the following options:
Completely removing the function
Commenting the function body
Keeping the function but deleting all the code
Using the exit as first statement makes it very hard to spot, you can easily read over it.
Fear of null (this also can lead to serious problems):
if (name != null)
person.Name = name;
Redundant if's (not using else):
if (!IsPostback)
{
// do something
}
if (IsPostback)
{
// do something else
}
Redundant checks (Split never returns null):
string[] words = sentence.Split(' ');
if (words != null)
More on checks (the second check is redundant if you are going to loop)
if (myArray != null && myArray.Length > 0)
foreach (string s in myArray)
And my favorite for ASP.NET: Scattered DataBinds all over the code in order to make the page render.
Copy paste redundancy:
if (x > 0)
{
// a lot of code to calculate z
y = x + z;
}
else
{
// a lot of code to calculate z
y = x - z;
}
instead of
if (x > 0)
y = x + CalcZ(x);
else
y = x - CalcZ(x);
or even better (or more obfuscated)
y = x + (x > 0 ? 1 : -1) * CalcZ(x)
Allocating elements on the heap instead of the stack.
{
char buff = malloc(1024);
/* ... */
free(buff);
}
instead of
{
char buff[1024];
/* ... */
}
or
{
struct foo *x = (struct foo *)malloc(sizeof(struct foo));
x->a = ...;
bar(x);
free(x);
}
instead of
{
struct foo x;
x.a = ...;
bar(&x);
}
The most common redundant code construct I see is code that is never called from anywhere in the program.
The other is design patterns used where there is no point in using them. For example, writing "new BobFactory().createBob()" everywhere, instead of just writing "new Bob()".
Deleting unused and unnecessary code can massively improve the quality of the system and the team's ability to maintain it. The benefits are often startling to teams who have never considered deleting unnecessary code from their system. I once performed a code review by sitting with a team and deleting over half the code in their project without changing the functionality of their system. I thought they'd be offended but they frequently asked me back for design advice and feedback after that.
I often run into the following:
function foo() {
if ( something ) {
return;
} else {
do_something();
}
}
But it doesn't help telling them that the else is useless here. It has to be either
function foo() {
if ( something ) {
return;
}
do_something();
}
or - depending on the length of checks that are done before do_something():
function foo() {
if ( !something ) {
do_something();
}
}
From nightmarish code reviews.....
char s[100];
followed by
memset(s,0,100);
followed by
s[strlen(s)] = 0;
with lots of nasty
if (strcmp(s, "1") == 0)
littered about the code.
Using an array when you want set behavior. You need to check everything to make sure its not in the array before you insert it, which makes your code longer and slower.
Redundant .ToString() invocations:
const int foo = 5;
Console.WriteLine("Number of Items: " + foo.ToString());
Unnecessary string formatting:
const int foo = 5;
Console.WriteLine("Number of Items: {0}", foo);

Resources