Unable to get objects to collide - c#

For the life of me, I cannot figure out what I am doing wrong. I have managed to make a player and make it shoot. I've also managed to make balls spawn in at random locations/speeds in the picture box.
I can't get any Collision to work. I am trying to keep all balls in the picture box and bounce back and also bounce off each other, and then destroy them when shot.
I have been trying to use Ball.Bounds.IntersectsWith(pictureBox2.Bounds), but it seems that Ball.bounds is wrong.
I have a vague idea why it is wrong but not definitive. My property bounds in box.cs is either wrong or I don't know how to make that relate to positioning all my balls.
A little nudge in the right direction would be appreciated as I have been stuck on this issue for a while now.
ball.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace shootyarcher
{
class Ball : Box
{
public string bounds { get; set; }
static private Random generator = new Random();
private int countdown;
public Ball ()
{
pic = Properties.Resources.Balloon;
x = generator.Next(60, 1920);
y = generator.Next(100, 1000);
xspeed = generator.Next(-10, 4);
yspeed = generator.Next(-10, 4);
countdown = generator.Next(100, 200);
}
public new void Move()
{
countdown--;
if (countdown == 0)
{
xspeed = generator.Next(-4, 4);
yspeed = generator.Next(-4, 4);
countdown = generator.Next(20, 40);
}
x = x + xspeed;
y = y + yspeed;
}
}
}
box.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing; //pictures
namespace shootyarcher
{
class Box
{
public float x;
public float y;
public float w;
public float h;
public float xspeed;
public float yspeed;
public Image pic;
public Box() // constructor
{
x = 0;
y = 0;
xspeed = 0;
yspeed = 0;
}
public void Move()
{
x = x + xspeed;
y = y + yspeed;
}
public void Draw(Graphics g)
{
g.DrawImage (pic, x, y);
}
public float Width()
{
return pic.Width;
}
public float Height()
{
return pic.Height;
}
public float Left()
{
return x;
}
public float Right()
{
return x + Width();
}
public float Top()
{
return y;
}
public float Bottom()
{
return y + Height();
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace shootyarcher
{
public partial class Form1 : Form
{
Archer player;
List<Arrow> Shiv;
List<Ball> Kill;
public Form1()
{
InitializeComponent();
Cursor.Hide();
this.FormBorderStyle = FormBorderStyle.None;
this.TopMost = true;
this.Bounds = Screen.PrimaryScreen.Bounds;
player = new Archer(0, 0);
Shiv = new List<Arrow>();
Kill = new List<Ball>();
for (int i = 0; i < 400; i++)
{
Ball temp = new Ball();
Kill.Add(temp);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
player.Move();
foreach (Arrow t in Shiv)
{
t.Move();
}
foreach (Ball m in Kill)
{
m.Move();
}
pictureBox1.Invalidate();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
player.moveup = true;
}
if (e.KeyCode == Keys.S)
{
player.movedown = true;
}
if (e.KeyCode == Keys.Space)
{
Arrow temp = new Arrow(player.x, player.y);
Shiv.Add(temp);
}
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
player.moveup = false;
}
if (e.KeyCode == Keys.S)
{
player.movedown = false;
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
player.Draw(e.Graphics);
foreach (Arrow t in Shiv)
{
t.Draw(e.Graphics);
}
foreach (Ball m in Kill)
{
m.Draw(e.Graphics);
}
}
}
}

Related

How to Instantiate circles all over the canvas unity(Mandelbrot set)

i am trying to Make The Mandelbrot set, i have the function thing working, zn = zn^
and i want to Visualizing the Mandelbrot set using circles, i tried this code but it cruses every time i compile, here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PaintMand : MonoBehaviour
{
[SerializeField] private GameObject CirclePaint;
[SerializeField] private RectTransform RedCircle;
[SerializeField] private Canvas canvas;
private float sumDistance = 0;
private bool HasFinshed = false;
private Vector2 start = new Vector2(2.133f,0.976f);
private void Update()
{
if (!HasFinshed)
{
sumDistance = AutoAxis.GetSumDistance();
MoveRed();
LoadRed();
}
}
public void MoveRed()
{
if(start.y < -0.988f)
{
HasFinshed = true;
}
else if(start.x <= -2.107f)
{
start.x = 2.133f;
start.y -= 0.20f;
}
else
{
start.x -= 0.20f;
}
RedCircle.anchoredPosition = start;
}
public void LoadRed()
{
if (IsUnstable())
{
GameObject NewCircle = Instantiate(CirclePaint, Vector3.zero,Quaternion.identity);
NewCircle.GetComponent<Image>().color = new Color(sumDistance,sumDistance,sumDistance);
NewCircle.transform.SetParent(canvas.transform);
NewCircle.GetComponent<RectTransform>().anchoredPosition = RedCircle.anchoredPosition;
}
}
private bool IsUnstable()
{
if(sumDistance > 1000)
{
return true;
}
return false;
}
}
the red circle is the c in the equation, zn = zn^ + c
and it moves every frame and checks if its unstable(the autoaxis is the class that makes the Visualizing the function) it gets the sum of the distance between all the circles and sends the float to the paintmad class, this cruses every time, pls help :(

My bullets never draw on screen?

I'm making a Space Invaders copy in XNA. I have my playerShip class that handles movement and sprite animation. Today I decided to make my ship shoot. I created a class to hold my bullets logic and initialized/updated them in my playShip class. So my problem is that when I build and debug, I press the key for shooting (in my case, X) but the bullets are never drawn on the screen. I've put a breakpoint on my Draw() call and there wasn't an exception. This means the code was never executed. Here is my ship class:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
namespace SpaceInvaders
{
class playerShip
{
public static Texture2D playerShipTex, bulletsTex;
public static Rectangle playerShipHitBox;
public static Vector2 playerShipPos = new Vector2(369, 546), playerShipOrigin;
int playerShipCurrentFrame = 1, playerShipFrameWidth = 62, playerShipFrameHeight = 86;
public float spriteTimer = 0f, spriteInterval = 100f, bulletDelay;
public List<blasterLasers> bulletsList;
public playerShip()
{
bulletsList = new List<blasterLasers>();
bulletDelay = 20f;
}
public void LoadContent(ContentManager Content)
{
playerShipTex = Content.Load<Texture2D>(".\\gameGraphics\\gameSprites\\playerShip\\playerShipSpriteSheet");
bulletsTex = Content.Load<Texture2D>(".\\gameGraphics\\gameSprites\\playerShip\\playerShipBlaster");
}
public void Update(GameTime gameTime)
{
playerShipHitBox = new Rectangle(playerShipCurrentFrame * playerShipFrameWidth, 0, playerShipFrameWidth, playerShipFrameHeight);
playerShipOrigin = new Vector2(playerShipHitBox.X / 2, playerShipHitBox.Y / 2);
MouseState mouseState = Mouse.GetState();
KeyboardState keyboardState = Keyboard.GetState();
spriteTimer += (float)gameTime.ElapsedGameTime.Milliseconds;
if (spriteTimer > spriteInterval)
{
playerShipCurrentFrame++;
spriteTimer = 0f;
}
if (playerShipCurrentFrame == 2)
{
playerShipCurrentFrame = 0;
}
playerShipHitBox = new Rectangle(playerShipCurrentFrame * playerShipFrameWidth, 0, playerShipFrameWidth, playerShipFrameHeight);
playerShipOrigin = new Vector2(playerShipHitBox.Width / 2, playerShipHitBox.Height / 2);
if (keyboardState.IsKeyDown(Keys.X))
{
Shoot();
}
UpdateBullets();
if (keyboardState.IsKeyDown(Keys.Right))
{
playerShipPos.X += 3;
}
if (keyboardState.IsKeyDown(Keys.Left))
{
playerShipPos.X -= 3;
}
if (keyboardState.IsKeyDown(Keys.Down))
{
playerShipPos.Y += 3;
}
if (keyboardState.IsKeyDown(Keys.Up))
{
playerShipPos.Y -= 3;
}
if (playerShipPos.X <= 0)
{
playerShipPos.X = 0;
}
if (playerShipPos.X + playerShipTex.Width >= 1110)
{
playerShipPos.X = 1110 - playerShipTex.Width;
}
if (playerShipPos.Y <= 48)
{
playerShipPos.Y = 48;
}
if (playerShipPos.Y + playerShipTex.Height >= Game1.screenHeight)
{
playerShipPos.Y = Game1.screenHeight - playerShipTex.Height;
}
}
public void Shoot()
{
if (bulletDelay >= 0)
{
bulletDelay--;
}
if (bulletDelay <= 0)
{
blasterLasers newBullet = new blasterLasers(bulletsTex);
newBullet.spritePos = new Vector2(playerShipPos.X + 14 - newBullet.spriteTex.Width / 2, playerShipPos.Y);
newBullet.isVisible = true;
if (bulletsList.Count() > 20)
{
bulletsList.Add(newBullet);
}
}
if (bulletDelay == 0)
{
bulletDelay = 20;
}
}
public void UpdateBullets()
{
foreach (blasterLasers bulletsSpawn in bulletsList)
{
bulletsSpawn.spritePos.Y = bulletsSpawn.spritePos.Y - bulletsSpawn.spriteSpeed;
if (bulletsSpawn.spritePos.Y == 0)
{
bulletsSpawn.isVisible = false;
}
}
for (int i = 0; i < bulletsList.Count(); i++)
{
if (!bulletsList[i].isVisible)
{
bulletsList.RemoveAt(i);
i--;
}
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(playerShipTex, playerShipPos, playerShipHitBox, Color.White, 0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0);
foreach (blasterLasers bulletsSpawn in bulletsList)
{
bulletsSpawn.Draw(spriteBatch);
}
}
}
}
And here's my blaster class:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
namespace SpaceInvaders
{
public class blasterLasers
{
public Rectangle boundingBox;
public Texture2D spriteTex;
public Vector2 spriteOrigin, spritePos;
public bool isVisible;
public float spriteSpeed;
public blasterLasers(Texture2D newSpriteTex)
{
spriteSpeed = 10f;
spriteTex = newSpriteTex;
isVisible = false;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(spriteTex, spritePos, Color.White);
}
}
}
And finally I initalize the playerShip class and Update()/Draw() it in my Game1 class.
I don't understand this line if (bulletsList.Count() > 20). What does it do? I mean, if there is no bullets already on the field, you can't fire new ones?
-- OTHER PROBLEM
Then you ask if if (bulletsSpawn.spritePos.Y == 0). But position.Y is never 0, it's only above 0 or goes under 0. So change that == to <=

How to implement movement in a chess game ?

I am learning to make a small variant of chess game using windows forms C#, the game includes only the pawns of both sides, i have drew the board and organized the pieces on there places, but i honestly do not know how to start implementing the moves by clicking the mouse on the piece and then the location where i want to move it.
as references the black pawn is named piece, and white pawn is named pieceW
here is my code for the board
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AIchess
{
public partial class Form1 : Form
{
static System.Drawing.Bitmap piece = AIchess.Properties.Resources.piece;
ChessPiece Piece = new ChessPiece(piece, ChessColor.Black);
static System.Drawing.Bitmap pieceW = AIchess.Properties.Resources.pieceW;
ChessPiece PieceW = new ChessPiece(pieceW, ChessColor.White);
Square[,] square = new Square[8, 8];
public Form1()
{
InitializeComponent();
int i, j;
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
this.square[i, j] = new Square();
this.square[i, j].BackColor = System.Drawing.SystemColors.ActiveCaption;
this.square[i, j].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.square[i, j].Location = new System.Drawing.Point(57 + i * 60, 109 + j * 60);
this.square[i, j].Name = i.ToString()+j.ToString();
this.square[i, j].Size = new System.Drawing.Size(60, 60);
this.square[i, j].TabIndex = 2;
this.square[i, j].TabStop = false;
this.Controls.Add(this.square[i, j]);
if (j == 1)
{
this.square[i, j].Image = piece;
this.square[i, j].AllocatedBy = "black";
}
if (j == 6)
{
this.square[i, j].Image = pieceW;
this.square[i, j].AllocatedBy = "white";
}
if (((i+j) % 2) ==0)
this.square[i, j].BackColor = Color.RoyalBlue;
else
this.square[i, j].BackColor = Color.LightBlue;
}
}
}
}
public enum ChessColor
{
White,
Black,
};
class ChessPiece
{
private Image DisplayedImage;
private ChessColor DisplayedColor;
private Point CurrentSquare;
public ChessPiece(Image image, ChessColor color)
{
DisplayedImage = image;
DisplayedColor = color;
}
}
class Square:PictureBox
{
private bool color;
public string AllocatedBy;
}
}
Here's a really simple implementation, I hope you won't mind that I did it from scratch.
Obviously it's very simple, there's no drag and drop and no animation but it fulfills your requirement.
I'll go through each part and explain them
InitializeGame
There you do set your images dimensions (they should be identical obviously)
You add in the dictionary the relationship between piece type/color and your bitmap
Note : the grid will be scaled so you can throw any size of bitmap you like
CreateBoard, DrawGame, DrawPieces
Nothing exceptional in there, note that for keeping things simple I do that every time a user clicks but it shouldn't be much of an issue, it's not Crysis after all :D
PickOrDropPiece
This is the logic where picking/dropping happens, it's really trivial and I'll let you take a look by yourself.
Differences between your code
I've created a Board type which holds the pieces and that you can easily update.
Note : do not remove the equality members in Piece they are here to help the dictionary.
Make sure to use 32-bit bitmaps with transparent borders
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
pictureBox1.MouseDown += pictureBox1_MouseDown;
}
#region Properties
private Board Board { get; set; }
private Piece CurrentPiece { get; set; }
private Dictionary<Piece, Bitmap> PieceBitmaps { get; set; }
private int TileWidth { get; set; }
private int TileHeight { get; set; }
#endregion
#region Events
private void Form1_Load(object sender, EventArgs e)
{
InitializeGame();
DrawGame();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
PickOrDropPiece(e);
DrawGame();
}
#endregion
#region Methods
private void InitializeGame()
{
TileWidth = 64;
TileHeight = 64;
Board = new Board();
PieceBitmaps = new Dictionary<Piece, Bitmap>();
PieceBitmaps.Add(new Piece(PieceType.Pawn, PieceColor.Black), new Bitmap("pawnblack.png"));
PieceBitmaps.Add(new Piece(PieceType.Pawn, PieceColor.White), new Bitmap("pawnwhite.png"));
}
private void DrawGame()
{
var tileSize = new Size(TileWidth, TileHeight);
Bitmap bitmap = CreateBoard(tileSize);
DrawPieces(bitmap);
pictureBox1.Image = bitmap;
}
private Bitmap CreateBoard(Size tileSize)
{
int tileWidth = tileSize.Width;
int tileHeight = tileSize.Height;
var bitmap = new Bitmap(tileWidth*8, tileHeight*8);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
Brush brush = (x%2 == 0 && y%2 == 0) || (x%2 != 0 && y%2 != 0) ? Brushes.Black : Brushes.White;
graphics.FillRectangle(brush, new Rectangle(x*tileWidth, y*tileHeight, tileWidth, tileHeight));
}
}
}
return bitmap;
}
private void DrawPieces(Bitmap bitmap)
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
Board board = Board;
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
Piece piece = board.GetPiece(x, y);
if (piece != null)
{
Bitmap bitmap1 = PieceBitmaps[piece];
graphics.DrawImageUnscaled(bitmap1, new Point(x*TileWidth, y*TileHeight));
}
}
}
}
}
private void PickOrDropPiece(MouseEventArgs e)
{
Point location = e.Location;
int x = location.X/TileWidth;
int y = location.Y/TileHeight;
bool pickOrDrop = CurrentPiece == null;
if (pickOrDrop)
{
// Pick a piece
Piece piece = Board.GetPiece(x, y);
Board.SetPiece(x, y, null);
if (piece != null)
{
label1.Text = string.Format("You picked a {0} {1} at location {2},{3}", piece.Color, piece.Type, x,
y);
}
else
{
label1.Text = "Nothing there !";
}
CurrentPiece = piece;
}
else
{
// Drop picked piece
Board.SetPiece(x, y, CurrentPiece);
label1.Text = string.Format("You dropped a {0} {1} at location {2},{3}", CurrentPiece.Color,
CurrentPiece.Type, x,
y);
CurrentPiece = null;
}
}
#endregion
}
public class Board
{
private readonly Piece[] _pieces;
public Board()
{
_pieces = new Piece[8*8];
PopulatePieces();
}
public Piece GetPiece(int x, int y)
{
int i = y*8 + x;
return _pieces[i];
}
public void SetPiece(int x, int y, Piece piece)
{
int i = y*8 + x;
_pieces[i] = piece;
}
private void PopulatePieces()
{
for (int i = 0; i < 8; i++)
{
SetPiece(i, 1, new Piece(PieceType.Pawn, PieceColor.Black));
SetPiece(i, 7, new Piece(PieceType.Pawn, PieceColor.White));
}
}
}
public class Piece
{
private readonly PieceColor _color;
private readonly PieceType _type;
public Piece(PieceType type, PieceColor color)
{
_type = type;
_color = color;
}
public PieceType Type
{
get { return _type; }
}
public PieceColor Color
{
get { return _color; }
}
protected bool Equals(Piece other)
{
return _color == other._color && _type == other._type;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((Piece) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((int) _color*397) ^ (int) _type;
}
}
public static bool operator ==(Piece left, Piece right)
{
return Equals(left, right);
}
public static bool operator !=(Piece left, Piece right)
{
return !Equals(left, right);
}
}
public enum PieceType
{
Pawn
}
public enum PieceColor
{
Black,
White
}
}

Display vector co-ordinates as String values [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am right now trying to display a vector holding an X and Y value, for a sprite, from one class Game Object.cs to Game1.cs. I move a protected value (protected Vector2 velocity;) to a public Vector2 velocity when I move it over the draw method (so that it will show how fast the sprite on screen is moving) it comes up with Error 1 An object reference is required for the non-static field, method, or property. So I add static, now it's public static Vector2 velocitys, and play the game. When I look at the X and Y value, they'er there but will not change when I move. I have had this problem on anything with a static.
Is there a way to get rid of the static, or fix this so I can see the X and Y update while I am playing? I have the velocitys Vector take velocity's X and Y in the update in GameObject.cs so that it will constantly take from velocity.
Why does it need a static? Can I change that? Can I update it on the screen?
This is the code:
GameObject.cs:
(Holdes the Vectors velocitys and velocity)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Tile_Engine;
namespace **
{
public class GameObject
{
#region Declarations
protected Vector2 worldLocation;
protected Vector2 velocity;
protected int frameWidth;
protected int frameHeight;
protected bool enabled;
protected bool flipped = false;
protected bool onGround;
protected Rectangle collisionRectangle;
protected int collideWidth;
protected int collideHeight;
protected bool codeBasedBlocks = true;
protected float drawDepth = 0.85f;
protected Dictionary<string, AnimationStrip> animations =
new Dictionary<string, AnimationStrip>();
protected string currentAnimation;
public Vector2 velocitys;
#endregion
#region Properties
public bool Enabled
{
get { return enabled; }
set { enabled = value; }
}
public Vector2 WorldLocation
{
get { return worldLocation; }
set { worldLocation = value; }
}
public Vector2 WorldCenter
{
get
{
return new Vector2(
(int)worldLocation.X + (int)(frameWidth / 2),
(int)worldLocation.Y + (int)(frameHeight / 2));
}
}
public Rectangle WorldRectangle
{
get
{
return new Rectangle(
(int)worldLocation.X,
(int)worldLocation.Y,
frameWidth,
frameHeight);
}
}
public Rectangle CollisionRectangle
{
get
{
return new Rectangle(
(int)worldLocation.X + collisionRectangle.X,
(int)worldLocation.Y + collisionRectangle.Y,
collisionRectangle.Width,
collisionRectangle.Height);
}
set { collisionRectangle = value; }
}
#endregion
#region Helper Methods
private void updateAnimation(GameTime gameTime)
{
if (animations.ContainsKey(currentAnimation))
{
if (animations[currentAnimation].FinishedPlaying)
{
PlayAnimation(animations[currentAnimation].NextAnimation);
}
else
{
animations[currentAnimation].Update(gameTime);
}
}
}
#endregion
#region Public Methods
public void PlayAnimation(string name)
{
if (!(name == null) && animations.ContainsKey(name))
{
currentAnimation = name;
animations[name].Play();
}
}
public virtual void Update(GameTime gameTime)
{
if (!enabled)
return;
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
updateAnimation(gameTime);
if (velocity.Y != 0)
{
velocitys = velocity;
onGround = false;
}
Vector2 moveAmount = velocity * elapsed;
moveAmount = horizontalCollisionTest(moveAmount);
moveAmount = verticalCollisionTest(moveAmount);
Vector2 newPosition = worldLocation + moveAmount;
newPosition = new Vector2(
MathHelper.Clamp(newPosition.X, 0,
Camera.WorldRectangle.Width - frameWidth),
MathHelper.Clamp(newPosition.Y, 2 * (-TileMap.TileHeight),
Camera.WorldRectangle.Height - frameHeight));
worldLocation = newPosition;
}
public virtual void Draw(SpriteBatch spriteBatch)
{
if (!enabled)
return;
if (animations.ContainsKey(currentAnimation))
{
SpriteEffects effect = SpriteEffects.None;
if (flipped)
{
effect = SpriteEffects.FlipHorizontally;
}
spriteBatch.Draw(
animations[currentAnimation].Texture,
Camera.WorldToScreen(WorldRectangle),
animations[currentAnimation].FrameRectangle,
Color.White, 0.0f, Vector2.Zero, effect, drawDepth);
}
}
#endregion
#region Map-Based Collision Detecting Methods
private Vector2 horizontalCollisionTest(Vector2 moveAmount)
{
if (moveAmount.X == 0)
return moveAmount;
Rectangle afterMoveRect = CollisionRectangle;
afterMoveRect.Offset((int)moveAmount.X, 0);
Vector2 corner1, corner2;
if (moveAmount.X < 0)
{
corner1 = new Vector2(afterMoveRect.Left,
afterMoveRect.Top + 1);
corner2 = new Vector2(afterMoveRect.Left,
afterMoveRect.Bottom - 1);
}
else
{
corner1 = new Vector2(afterMoveRect.Right,
afterMoveRect.Top + 1);
corner2 = new Vector2(afterMoveRect.Right,
afterMoveRect.Bottom - 1);
}
Vector2 mapCell1 = TileMap.GetCellByPixel(corner1);
Vector2 mapCell2 = TileMap.GetCellByPixel(corner2);
if (!TileMap.CellIsPassable(mapCell1) ||
!TileMap.CellIsPassable(mapCell2))
{
moveAmount.X = 0;
velocity.X = 0;
}
if (codeBasedBlocks)
{
if (TileMap.CellCodeValue(mapCell1) == "BLOCK" ||
TileMap.CellCodeValue(mapCell2) == "BLOCK")
{
moveAmount.X = 0;
velocity.X = 0;
}
}
return moveAmount;
}
private Vector2 verticalCollisionTest(Vector2 moveAmount)
{
if (moveAmount.Y == 0)
return moveAmount;
Rectangle afterMoveRect = CollisionRectangle;
afterMoveRect.Offset((int)moveAmount.X, (int)moveAmount.Y);
Vector2 corner1, corner2;
if (moveAmount.Y < 0)
{
corner1 = new Vector2(afterMoveRect.Left + 1,
afterMoveRect.Top);
corner2 = new Vector2(afterMoveRect.Right - 1,
afterMoveRect.Top);
}
else
{
corner1 = new Vector2(afterMoveRect.Left + 1,
afterMoveRect.Bottom);
corner2 = new Vector2(afterMoveRect.Right - 1,
afterMoveRect.Bottom);
}
Vector2 mapCell1 = TileMap.GetCellByPixel(corner1);
Vector2 mapCell2 = TileMap.GetCellByPixel(corner2);
if (!TileMap.CellIsPassable(mapCell1) ||
!TileMap.CellIsPassable(mapCell2))
{
if (moveAmount.Y > 0)
onGround = true;
moveAmount.Y = 0;
velocity.Y = 0;
}
if (codeBasedBlocks)
{
if (TileMap.CellCodeValue(mapCell1) == "BLOCK" ||
TileMap.CellCodeValue(mapCell2) == "BLOCK")
{
if (moveAmount.Y > 0)
onGround = true;
moveAmount.Y = 0;
velocity.Y = 0;
}
}
return moveAmount;
}
#endregion
}
}
Game1.cs:
(Draws the Vector2 velocity)
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Tile_Engine;
namespace **
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player player;
SpriteFont pericles8;
Vector2 scorePosition = new Vector2(20, 580);
enum GameState { TitleScreen, Playing, PlayerDead, GameOver };
GameState gameState = GameState.TitleScreen;
Vector2 gameOverPosition = new Vector2(350, 300);
Vector2 livesPosition = new Vector2(600, 580);
Vector2 Velocitys = new Vector2(100, 580);
Texture2D titleScreen;
float deathTimer = 0.0f;
float deathDelay = 5.0f;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
this.graphics.PreferredBackBufferWidth = 800;
this.graphics.PreferredBackBufferHeight = 600;
this.graphics.ApplyChanges();
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
TileMap.Initialize(
Content.Load<Texture2D>(#"Textures\PlatformTiles"));
TileMap.spriteFont =
Content.Load<SpriteFont>(#"Fonts\Pericles8");
pericles8 = Content.Load<SpriteFont>(#"Fonts\Pericles8");
titleScreen = Content.Load<Texture2D>(#"Textures\TitleScreen");
Camera.WorldRectangle = new Rectangle(0, 0, 160 * 48, 12 * 48);
Camera.Position = Vector2.Zero;
Camera.ViewPortWidth = 800;
Camera.ViewPortHeight = 600;
player = new Player(Content);
LevelManager.Initialize(Content, player);
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
KeyboardState keyState = Keyboard.GetState();
GamePadState gamepadState = GamePad.GetState(PlayerIndex.One);
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
if (gameState == GameState.TitleScreen)
{
if (keyState.IsKeyDown(Keys.Space) ||
gamepadState.Buttons.A == ButtonState.Pressed)
{
StartNewGame();
gameState = GameState.Playing;
}
}
if (gameState == GameState.Playing)
{
player.Update(gameTime);
LevelManager.Update(gameTime);
if (player.Dead)
{
if (player.LivesRemaining > 0)
{
gameState = GameState.PlayerDead;
deathTimer = 0.0f;
}
else{
gameState = GameState.GameOver;
deathTimer = 0.0f;
}
}
}
if (gameState == GameState.PlayerDead)
{
player.Update(gameTime);
LevelManager.Update(gameTime);
deathTimer = elapsed;
if (deathTimer > deathDelay)
{
player.WorldLocation = Vector2.Zero;
LevelManager.ReloadLevel();
player.Revive();
gameState = GameState.Playing;
}
}
if (gameState == GameState.GameOver)
{
deathTimer += elapsed;
if (deathTimer > deathDelay)
{
gameState = GameState.TitleScreen;
}
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
// TODO: Add your drawing code here
spriteBatch.Begin(
SpriteSortMode.BackToFront,
BlendState.AlphaBlend);
if (gameState == GameState.TitleScreen)
{
spriteBatch.Draw(titleScreen, Vector2.Zero, Color.White);
}
if ((gameState == GameState.Playing) ||
(gameState == GameState.PlayerDead) ||
(gameState == GameState.GameOver))
{
TileMap.Draw(spriteBatch);
player.Draw(spriteBatch);
LevelManager.Draw(spriteBatch);
spriteBatch.DrawString(
pericles8,
"Score: " + player.Score.ToString(),
scorePosition,
Color.White);
spriteBatch.DrawString(
pericles8,
"Lives Remaining: " + player.LivesRemaining.ToString(),
livesPosition,
Color.White);
spriteBatch.DrawString(
pericles8,
"Velocity: " + GameObject.velocitys.ToString(),
Velocitys,
Color.White);
}
if (gameState == GameState.PlayerDead)
{
}
if (gameState == GameState.GameOver)
{
spriteBatch.DrawString(
pericles8,
"G A M E O V E R !",
gameOverPosition,
Color.White);
}
spriteBatch.End();
base.Draw(gameTime);
}
private void StartNewGame()
{
player.Revive();
player.LivesRemaining = 3;
player.WorldLocation = Vector2.Zero;
LevelManager.LoadLevel(0);
}
}
}
Player.cs:
(A part of the velocity)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
using Tile_Engine;
namespace **
{
public class Player : GameObject
{
#region Declarations
private Vector2 fallSpeed = new Vector2(0, 20);
private float moveScale = 180.0f;
private bool dead = false;
public int score = 0;
private int livesRemaining = 3;
#endregion
public bool Dead
{
get { return dead; }
}
public int Score
{
get { return score; }
set { score = value; }
}
public int LivesRemaining
{
get { return livesRemaining; }
set { livesRemaining = value; }
}
public void Kill()
{
PlayAnimation("die");
LivesRemaining--;
velocity.X = 0;
dead = true;
}
public void Revive()
{
PlayAnimation("idle");
dead = false;
}
#region Constructor
public Player(ContentManager content)
{
animations.Add("idle",
new AnimationStrip(
content.Load<Texture2D>(#"Textures\Sprites\Player\Idle"),
48,
"idle"));
animations["idle"].LoopAnimation = true;
animations.Add("run",
new AnimationStrip(
content.Load<Texture2D>(#"Textures\Sprites\Player\Run"),
48,
"run"));
animations["run"].LoopAnimation = true;
animations.Add("jump",
new AnimationStrip(
content.Load<Texture2D>(#"Textures\Sprites\Player\Jump"),
48,
"jump"));
animations["jump"].LoopAnimation = false;
animations["jump"].FrameLength = 0.08f;
animations["jump"].NextAnimation = "idle";
animations.Add("die",
new AnimationStrip(
content.Load<Texture2D>(#"Textures\Sprites\Player\Die"),
48,
"die"));
animations["die"].LoopAnimation = false;
frameWidth = 48;
frameHeight = 48;
CollisionRectangle = new Rectangle(9, 1, 30, 46);
drawDepth = 0.825f;
enabled = true;
codeBasedBlocks = false;
PlayAnimation("idle");
}
#endregion
#region Public Methods
public override void Update(GameTime gameTime)
{
if (!Dead)
{
string newAnimation = "idle";
velocity = new Vector2(0, velocity.Y);
GamePadState gamePad = GamePad.GetState(PlayerIndex.One);
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Left) ||
(gamePad.ThumbSticks.Left.X < -0.3f))
{
flipped = false;
newAnimation = "run";
velocity = new Vector2(-moveScale, velocity.Y);
}
if (keyState.IsKeyDown(Keys.Right) ||
(gamePad.ThumbSticks.Left.X > 0.3f))
{
flipped = true;
newAnimation = "run";
velocity = new Vector2(moveScale, velocity.Y);
}
if (newAnimation != currentAnimation)
{
PlayAnimation(newAnimation);
}
if (keyState.IsKeyDown(Keys.Space) ||
(gamePad.Buttons.A == ButtonState.Pressed))
{
if (onGround)
{
Jump();
newAnimation = "jump";
}
}
if (currentAnimation == "jump")
newAnimation = "jump";
if (keyState.IsKeyDown(Keys.Up) ||
gamePad.ThumbSticks.Left.Y > 0.3f)
{
checkLevelTransition();
}
}
velocity += fallSpeed;
repositionCamera();
base.Update(gameTime);
}
public void Jump()
{
velocity.Y = -500;
}
#endregion
#region Helper Methods
private void repositionCamera()
{
int screenLocX = (int)Camera.WorldToScreen(worldLocation).X;
if (screenLocX > 500)
{
Camera.Move(new Vector2(screenLocX - 500, 0));
}
if (screenLocX < 200)
{
Camera.Move(new Vector2(screenLocX - 200, 0));
}
}
private void checkLevelTransition()
{
Vector2 centerCell = TileMap.GetCellByPixel(WorldCenter);
if (TileMap.CellCodeValue(centerCell).StartsWith("T_"))
{
string[] code = TileMap.CellCodeValue(centerCell).Split('_');
if (code.Length != 4)
return;
LevelManager.LoadLevel(int.Parse(code[1]));
WorldLocation = new Vector2(
int.Parse(code[2]) * TileMap.TileWidth,
int.Parse(code[3]) * TileMap.TileHeight);
LevelManager.RespawnLocation = WorldLocation;
velocity = Vector2.Zero;
}
}
#endregion
}
}
I have figured out for my self, I mostly wanted a quick answer. Just making a public vector does not help, I needed a method to transfer over the Vector:
public Vector2 Velocitys
{
get { return velocity; }
set { velocity = value; }
}
Then just like the public int Score method I draw it:
spriteBatch.DrawString(
pericles8,
"Velocity: " + player.Velocitys.ToString(),
Velocitys,
Color.White);
It works like a charm.
(Its pretty Ironic that the one thing that I asked why I would use it (get and set) would be the answer)

Collision between circle and a radius

I need to implement collision detection here. The objects i have here are a ball/circle and a rectangle. The balls are moving vertically, while the rectangle is moving horizontally. The condition is that if the ball and rectangle touch each other then an event should be raised. I have been trying to do that for a while with my colleague but without success. This is my first program in C# so please bear with me.
here is my code:
public partial class Form1 : Form
{
bool collided = false;
Player player;
List<Ball> balls;
const int fps = 60;
public Form1()
{
InitializeComponent();
balls = new List<Ball>();
Random r = new Random();
for(int i =0; i<1;i ++)
{
balls.Add(new Ball(Width, Height,r));
}
var task = new Task(Run);
task.Start();
player = new Player()
{
x = this.Width/2,
y = (Height*9/10),
xvel = 10,
brush = Brushes.Black,
};
}
protected void Run()
{
while (true)
{
for(int i = 0; i < balls.Count; i++)
{
balls[i].Move(this.Width);
}
this.Invalidate();
Thread.Sleep(1000 / fps);
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.Clear(Color.White);
for(int i = 0; i < balls.Count; i++)
{
balls[i].Draw(g);
}
player.DrawPlayer(g);
}
//This is the part where i was trying to check collision between the circle and a ball
private void CheckCollision(PaintEventArgs e)
{
if (player.IntersectsWith(balls))
{
player.Intersect(balls);
if (!player.IsEmpty)
{
collided = true;
MessageBox.Show("collision detected");
}
}
}
}
public class Player
{
public float x, y, xvel;
public Brush brush;
public Player()
{
}
public void DrawPlayer(Graphics g)
{
g.FillRectangle(brush, new RectangleF(x, y, 30,30));
}
public void MovePlayerLeft(int gameWidth)
{
if (x > 0)
{
x -= xvel;
}
}
public void MovePlayerRight(int gameWidth)
{
if (x < gameWidth-47)
{
x += xvel;
}
}
}
public class Ball
{
public float x, y, yvel, radius;
public Brush brush;
public Ball(int gamewidth,int gameHeight,Random r)
{
x = r.Next(gamewidth);
y = r.Next(gameHeight);
yvel = r.Next(2) + 5;
radius = r.Next(10) + 5;
brush = new SolidBrush(Color.Blue);
}
public void Move(int gameHeight)
{
if (y + radius >= gameHeight)
{
y = 0;
}
y += yvel;
}
public void Draw(Graphics g)
{
g.FillEllipse(brush, new RectangleF(x-radius,y - radius, radius * 2, radius * 2));
}
}
If you're trying to figure out if a rectangle and a circle is intersecting, try this algorithm for each of the four sides:
Circle line-segment collision detection algorithm?
You can probably speed this up by checking if corners are inside the circle.
Also, remember that a circle completely inside a rectangle and vice versa should probably count as a collision.

Categories

Resources