Check if Picturebox touches any object on screen C# - c#

I have a problem with my game that is coded on C#. I've tried searching all over the forums for this problem but none has worked for this case :/
I'm trying to check if Picturebox hits ANY other Picturebox in screen.
I've tried this, but this might be too slow when I add more objects.
if (!square.Bounds.IntersectsWith(grass.Bounds) && !square.Bounds.IntersectsWith(grMiddle.Bounds) && !square.Bounds.IntersectsWith(grRight.Bounds) && !square.Bounds.IntersectsWith(middle.Bounds) && !square.Bounds.IntersectsWith(sideRight.Bounds) && !square.Bounds.IntersectsWith(topPanel.Bounds))
This method doesn't work since player movement increases 100x and I die instantly, somehow...
foreach (PictureBox pic in this.Controls.OfType<PictureBox>())
{
if (pic != square) // exclude square PictureBox from the test
{
if (!square.Bounds.IntersectsWith(pic.Bounds))
{
if (!square.Bounds.IntersectsWith(rightGoal.Bounds))
{
if (Right) { square.Left += 5; }
if (Left) { square.Left -= 5; }
if (Up) { square.Top -= 5; }
if (Down) { square.Top += 5; }
}
else
{
pally.points++;
rightPoints.Text = pally.points.ToString();
square.Location = new Point(690, 533);
}
}
else
{
square.Location = new Point(690, 533);
}
}
}
I'm out of ideas, some help would be nice :)

if (Right) { square.Left += 5; }
if (Left) { square.Left -= 5; }
if (Up) { square.Top -= 5; }
if (Down) { square.Top += 5; }
Are these testing keyboard inputs or something? You're moving your square with this code. And you're doing it for each picturebox on your form. That's why your square moves too far. Separating your position updating code from your intersection code should solve your problem.

Related

Fire bullets at an interval continuously while the fire button is held down

In C# Unity3D, I'm trying to get my bullets to fire at an interval of bulletTime. Single shots work perfectly fine at the moment, but when I hold down the fire button, just 1 bullet is created and shot and then nothing else happens.
// Left mouse button HELD down.
else if (fireAgain && Input.GetMouseButton(0))
{
StartCoroutine("LoopNShoot");
fireAgain = false;
}
else if (timerH < bulletTime)
{
timerH += Time.deltaTime;
if(timerH >= bulletTime)
{
fireAgain = true;
timerH = 0;
}
}
IEnumerator LoopNShoot()
{
pivot.transform.Rotate(triggerAngle,0,0);
GameObject bullet = ObjectPooler.SharedInstance.GetPooledObject();
if (bullet != null) {
bullet.transform.position = SSpawn.transform.position;
bullet.transform.rotation = SSpawn.transform.rotation;
bullet.SetActive(true);
}
yield return new WaitForSeconds(.1f);
pivot.transform.rotation = Quaternion.Slerp(transform.rotation, originalRotationValue, Time.deltaTime * rotationResetSpeed);
}
Im thinking I need to place all my if statements and timer inside the coroutine? But that doesnt seem to help either...
Please ignore the pivot and rotation, it works fine for some animation, the only thing taht doesnt work is shooting bullets continuosly at a set interval while the fire button is Held down.
You should remove these else and just do.
private void Update()
{
if (fireAgain && Input.GetMouseButton(0))
{
StartCoroutine("LoopNShoot");
fireAgain = false;
timerH = 0;
}
if (timerH < bulletTime)
{
timerH += Time.deltaTime;
if(timerH >= bulletTime)
{
fireAgain = true;
}
}
}
You could also re-arange this to make clearer how it works:
private void Update()
{
if(!fireAgain)
{
timerH += Time.deltaTime;
if (timerH >= bulletTime)
{
fireAgain = true;
}
}
else
{
if(Input.GetMouseButton(0))
{
StartCoroutine("LoopNShoot");
fireAgain = false;
timerH = 0;
}
}
}
I actually thought you anyway already chose the Invoke method I showed you here

(Monogame) Update method causes extreme lag

I am currently creating a 2d platformer in monogame.
I created a block that, when hit by the player, starts dissapearing. When it dissapears, i draw a rectangle around it. Every Tile of the same type (BrittleTile) also starts dissapearing, untill the entire connected mob of BrittleTiles has dissapeared.
The problem is that for every BrittleTile that is destroyed, my game runs noticably slower, until it becomes a slideshow after 10 or so BrittleTiles destroyed. I have no idea as to what may cause this, i've been trying to ease the Update method of the class but nothing seems to help.
Any idea as to what may cause this?
class BrittleTile: Tile, IIncludeSound
{
public Rectangle DestroyedCheckRectangle;
private BrittleTile brittle;
private bool _isPlayed;
private bool _hasBroken;
private SoundEffect _sfxBreak;
private SoundEffectInstance _sfxiBreak;
private TimeSpan _breakTimer = new TimeSpan();
public Rectangle BrokenViewRectangle { get; set; }
private bool _isBreaking = false;
public BrittleTile(Texture2D texture, Rectangle baseViewRectangle, Rectangle brokenViewRectangle):base(texture, baseViewRectangle, true )
{
this.BrokenViewRectangle = brokenViewRectangle;
this.ViewRectangle = baseViewRectangle;
}
public void Update(GameTime gameTime, Hero hero, Entity[,] grid)
{
if (!this._hasBroken)
{
if (!this._isBreaking && !this._hasBroken && this.hasCollision)
_checkCollision(hero, grid);
if (this._isBreaking)
{
if (!this._isPlayed)
_sfxiBreak.Play();
this._isPlayed = true;
this._breakTimer += gameTime.ElapsedGameTime;
if (this._breakTimer.TotalMilliseconds < 250)
this.GhostMode(gameTime);
else
{
this._isBreaking = false;
this.hasCollision = false;
this._breakTimer -= this._breakTimer;
}
}
else
{
if (!this.hasCollision && this.DestroyedCheckRectangle.Width == 0)
{
this.DestroyedCheckRectangle.X = this.DestinationRectangle.X - 10;
this.DestroyedCheckRectangle.Y = this.DestinationRectangle.Y - 10;
this.DestroyedCheckRectangle.Height = this.DestinationRectangle.Height + 20;
this.DestroyedCheckRectangle.Width = this.DestinationRectangle.Width + 20;
this._hasBroken = true;
}
}
}
}
public override void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(this.Texture, this.DestinationRectangle, this.BrokenViewRectangle, Color.White);
if (this.hasCollision)
spriteBatch.Draw(this.Texture, this.DestinationRectangle, this.ViewRectangle, Color.White * this.GhostDraw * 0.9f);
spriteBatch.Draw(this.Texture, DestroyedCheckRectangle, new Rectangle(1, 1, 1, 1), Color.Yellow);
Console.WriteLine(this.DestroyedCheckRectangle.X + ", " + this.DestroyedCheckRectangle.Y + ", " + this.DestroyedCheckRectangle.Width + ", " + this.DestroyedCheckRectangle.Height);
}
private void _checkCollision(Hero hero, Entity[,] grid)
{
if (this.DestinationRectangle.Intersects(hero.AttackHitBox))
{
this._isBreaking = true;
}
foreach (Shuriken star in hero.Stars)
{
if (this.DestinationRectangle.Intersects(star.DestinationRectangle))
this._isBreaking = true;
}
foreach (Entity entityObject in grid)
{
if (hasCollision && entityObject.GetType() == typeof(BrittleTile)){
brittle = entityObject.DeepCopy() as BrittleTile;
if (this.DestinationRectangle.Intersects(brittle.DestroyedCheckRectangle))
this._isBreaking = true;
}
}
}
override public void LoadSounds(ContentManager content)
{
this._sfxBreak = content.Load<SoundEffect>("SFX/brittleBreak");
_sfxiBreak = _sfxBreak.CreateInstance();
_sfxiBreak.Volume = 0.2f;
}
}
First, this line:
if (!this._isBreaking && !this._hasBroken && this.hasCollision)
the !this._hasBroken is superfluous.
My first warning sign is this line:
brittle = entityObject.DeepCopy() as BrittleTile;
I assume DeepCopy() makes a new version of the object, and copies all it's properties, right? Seeing the code of that might help pin it down, but on that assumption...
For every Tile, you're cycling through every object in you're grid and you're completely duplicating that object as a BrittleTile, why?
My first change would be to modify that foreach to have this within it:
var brittle = entityObject as BrittleTile
if (brittle != null && hasCollision){
if (this.DestinationRectangle.Intersects(brittle.DestroyedCheckRectangle))
this._isBreaking = true;
}
}
Not sure this is the primary cause of the slowdown, but it is definitely an issue. If you're cloning an object and then immediately throwing an object away, you're almost certainly doing something wrong. If you're cloning an object and you're not editing the properties of that copy at all (and using those edits), you're definitely doing something wrong. I'd be wary before using a method like that unless you're really sure that's what you want.

Detecting collision between two rectangles on a WPF Canvas

I am extremely new to programming, and I have started off with C#. I am now trying to make my first game, I decided on snake. So far I have been trying to research this question, but all of the answers I see are ones that pertain to people who are using a different method of moving their snake around.
My program uses two doubles (left and top) in order to store where the snake is on the Canvas. My program also uses two doubles for the "food" in the game, called randomFoodSpawnLeft and randomFoodSpawnTop.
My question is this. How does one detect collision between two rectangular objects with just a left and top value? I am rather confused.
snakeWindow is the Window, snakeHead is the rectangle that represents a snake, left is the left value of the snake, top is the top value of the snake.
void timer_Tick(object sender, EventArgs e)
{
double left = Canvas.GetLeft(snakeHead);
double top = Canvas.GetTop(snakeHead);
if (keyUp)
{
top -= 3;
}
else if (keyDown)
{
top += 3;
}
else if (keyLeft)
{
left -= 3;
}
else if (keyRight)
{
left += 3;
}
// These statements see if you have hit the border of the window, default is 1024x765
if (left < 0)
{
left = 0;
gameOver = true;
}
if (top < 0)
{
top = 0;
gameOver = true;
}
if (left > snakeWindow.Width)
{
left = 0;
gameOver = true;
}
if (top > snakeWindow.Height)
{
top = 0;
gameOver = true;
}
// Statements that detect hit collision between the snakeHead and food
//
if (foodEaten == true)
{
spawnFood();
textBlockCurrentScore.Text += 1;
}
// If gameOver were to be true, then the game would have to end. In order to accomplish this I display to the user that the game is over
// and the snakeHead is disabled, and should restart.
if (gameOver == true)
{
keyRight = false;
keyLeft = false;
keyUp = false;
keyDown = false;
top = 0;
left = 0;
textBlockGameOver.Text = "GAME OVER!";
snakeCanvas.Background = Brushes.Blue;
}
Canvas.SetLeft(snakeHead, left);
Canvas.SetTop(snakeHead, top);
}
You can use System.Windows.Rect.IntersectsWith. Try it like this:
Rect rect1 = new Rect(left1, top1, widht1, height1);
Rect rect2 = new Rect(left2, top2, widht2, height2);
bool intersects = rect1.IntersectsWith(rect2);
Of course you will have to check the snake's head against all it's parts.

Issues with hand Clapping gesture

This my code for clapping hand gesture ,i use the result to set a robotic arm end effector to a 3d location for every clap)
i want the event handler to trigger just once for every clap gesture,
and reset for another clap gesture. but when i clap and my hands are close together, my event handler keeps firing!! please how do i correct this issue. could i use a reset method or something
[hand clap code]
float previousDistance = 0.0f;
private void MatchClappingGesture(Skeleton skeleton)
{
if (skeleton == null)
{
return;
}
if (skeleton.Joints[JointType.WristRight].TrackingState == JointTrackingState.Tracked && skeleton.Joints[JointType.WristLeft].TrackingState == JointTrackingState.Tracked)
{
float currentDistance = GetJointDistance(skeleton.Joints[JointType.WristRight], skeleton.Joints[JointType.WristLeft]);
{
if (currentDistance < 0.1f && previousDistance > 0.1f )
{
if (this.GestureRecognized != null)
{
this.GestureRecognized(this, new GestureEventArgs(RecognitionResult.Success));
previousDate = DateTime.Now;
}
}
previousDistance = currentDistance;
}
}
}
this is where i call the event handler
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
kinect = KinectSensor.KinectSensors[0];
kinect.Start();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Could not find Kinect Camera: " + ex.Message);
}
kinect.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
kinect.ColorStream.Enable(ColorImageFormat.RgbResolution1280x960Fps12);
kinect.SkeletonStream.Enable(new TransformSmoothParameters()
{
Correction = 0.5f,
JitterRadius = 0.05f,
MaxDeviationRadius = 0.05f,
Prediction = 0.5f,
Smoothing = 0.5f
});
kinect.AllFramesReady += Kinect_SkeletonAllFramesReady;
recognitionEngine = new GestureRecognitionEngine();
armEngine = new ArmControllerEngine();
recognitionEngine.GestureRecognized += new EventHandler<GestureEventArgs>(recognitionEngine_GestureRecognized);
}
event handler fires here
void recognitionEngine_GestureRecognized(object sender,
GestureEventArgs e)
{
//armEngine.setArm(raMove,port,servoId);
MessageBox.Show("HI");
}
the message box prints multiple time instead of just once!!please help
You must bear in mind that Kinect's measurements have a degree of inaccuracy. Also, in certain cases (like when the hands are together!!) that inaccuracy increases greatly, and the detected joint positions start jumping all over the place. Try it with the SDK's provided skeleton viewer and you'll see. This is often mitigated by using smoothing algorithms, but in your case that might not be the most adequate solution. Try increasing the distance you are using to detect the gesture, give it some 20cm or so (btw, what does your GetJointDistance returns? Meters? Then give it 0.2)
void wait(int a)
{
for (int i = 0; i < a; i++) ;
}
int count = 0;
void recognitionEngine_GestureRecognized(object sender, GestureEventArgs e)
{
wait(3);
clapShow();
}
//clap method
void clapShow()
{
count += 1;
if (count == 1)
{
MessageBox.Show("Gesture Capture Within >> " + time.Millisecond.ToString() + " milli Seconds");
}
count = 0 ;
}
}
I called the message box as a method every 3millsecs wait(3) so that slows down the the event handler.
Then set the count to "1" before a gesture then back to "0"after every clap gesture and it works pretty well!!
Note!.... The wait(X) method i created a simple loop that counts down to the value X. It can be any value based on the level of sensitivity level one desires. Thanks jose!!
i hope this helps someone..

Removing Elements Programmatically in Silverlight

I am starting to learn silverlight and to practice I am doing a simple space invaders type videogame.
My issue is I am creating custom controls (bullets) programmatically like so:
if(shooting)
{
if(currBulletRate == bulletRate)
{
Bullet aBullet = new Bullet();
aBullet.X = mouse.X - 5;
aBullet.Y = mouse.Y - Ship.Height;
aBullet.Width = 10;
aBullet.Height = 40;
aBullet.Tag = "Bullet";
LayoutRoot.Children.Add(aBullet);
currBulletRate = 0;
}
else
currBulletRate++;
}
However I am having trouble removing them once they go off bounds (leave the LayoutRoot).
I tried looping throught the LayoutRoot.Children and removing but I can't seem to get it right.
UIElement[] tmp = new UIElement[LayoutRoot.Children.Count];
LayoutRoot.Children.CopyTo(tmp, 0);
foreach (UIElement aElement in tmp)
{
Shape aShape = aElement as Shape;
if (aShape != null && aShape.Tag != null)
{
if (aShape.Tag.ToString().Contains("Bullet"))
{
if (Canvas.GetTop(aShape) + aShape.ActualHeight < 0) // This checks if it leaves the top
{
LayoutRoot.Children.Remove(aElement);
}
else if(Canvas.GetTop(aShape) > Canvas.ActualHeight) // This condition checks if it leaves the bottom
{
LayoutRoot.Children.Remove(aElement);
}
}
}
}
The code you pasted was only checking if the bullet left the top of the canvas.

Categories