How do I make a picturebox move and rotate within a groupbox? - c#

I am currently working on a topdown game made in windows forms. In the game, your character rotates after your mouse and you can shoot a shot from your character in the direction of your mouse. To create multiple areas in the game, I chose to use groupboxes as separate areas in the game that you can switch between using buttons but I've run in to a problem. I can no longer rotate or move my character or even shoot within the groupboxes.
I've tried setting breakpoints and discovered that the keyup, keydown and mousemove methods are not being called but I don't know why. For some reason I get an error when i release space in the btnSave_Click method which i marked in the code.
static Image originalImage;
bool pRight, pLeft, pUp, pDown;
string[] Saves;
Save[] RSaves = new Save[4];
Save yoursave;
Save temp;
int slot;
NewGame newgame;
SavedGames savedgames;
string savedata, name = "";
int lvl = 1;
double exp = 0, money = 0;
int pSpeed = 5;
double deltaY, deltaX;
float interval = 7;
Point start;
Point nextStart;
Point cursor;
float radian;
const double Rad2Grad = (180 / Math.PI);
public MainGame()
{
InitializeComponent();
pbPlayer.BringToFront();
gbxTown.AllowDrop = true;
gbxQ1.AllowDrop = true;
pbShot.Location = pbPlayer.Location;
// newgame = new NewGame();
// savedgames = new SavedGames();
originalImage = pbPlayer.Image;
}
public void setSaves(string savedata, int slot)
{
Saves = savedata.Split('#');
string a1 = Saves[0];
string a2 = Saves[1];
string a3 = Saves[2];
string a4 = Saves[3];
RSaves[0] = temp.StringToSaves(temp, a1);
RSaves[1] = temp.StringToSaves(temp, a2);
RSaves[2] = temp.StringToSaves(temp, a3);
RSaves[3] = temp.StringToSaves(temp, a4);
yoursave = RSaves[slot - 1];
name = yoursave.getName();
this.slot = slot;
Controls.Add(pbPlayer);
Controls.Add(pbShot);
}
private void MainGame_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.A)
{
pRight = false;
pLeft = true;
}
else if (e.KeyData == Keys.D)
{
pRight = true;
pLeft = false;
}
else if (e.KeyData == Keys.S)
{
pUp = true;
pDown = false;
}
else if (e.KeyData == Keys.W)
{
pUp = false;
pDown = true;
}
if (e.KeyData == Keys.Space)
{
start = pbPlayer.Location;
cursor = Cursor.Position;
nextStart = start;
deltaY = cursor.Y - start.Y;
deltaX = cursor.X - start.X;
double test = Angle(start, cursor);
radian = (float)(Angle(start, cursor) - 175);
timer2.Enabled = true;
}
}
private void MainGame_KeyUp_1(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.A)
{
pLeft = false;
}
else if (e.KeyData == Keys.D)
{
pRight = false;
}
else if (e.KeyData == Keys.S)
{
pUp = false;
}
else if (e.KeyData == Keys.W)
{
pDown = false;
}
if (e.KeyData == Keys.Space)
{
timer2.Stop();
pbShot.Location = start;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
MovePlayer();
//checkCollision();
}
private void btnNextArea_Click(object sender, EventArgs e)
{
pbPlayer.Parent = gbxQ1;
pbShot.Parent = gbxQ1;
gbxQ1.Location = new Point(0, 0);
gbxTown.Location = new Point(605, 0);
pbPlayer.Location = new Point(100, 200);
pbShot.Location = pbPlayer.Location;
}
private void btnSave_Click(object sender, EventArgs e)
{
newgame = new NewGame();
savedgames = new SavedGames();
RSaves[slot - 1] = new Save(name, money, lvl, exp);
for (int i = 0; i < 4; i++) //When the Spacebar is released, a System.IndexOutOfRangeException error happens for i.
{
Saves[i] = RSaves[i].SavesToString();
}
savedata = Saves[0] + Saves[1] + Saves[2] + Saves[3];
System.IO.File.WriteAllLines(#"saves.txt", Saves);
newgame.setSaves(savedata);
savedgames.setSaves(savedata);
}
private void btnBack_Click(object sender, EventArgs e)
{
pbPlayer.Parent = gbxTown;
pbShot.Parent = gbxTown;
gbxTown.Location = new Point(0, 0);
gbxQ1.Location = new Point(605, 0);
pbPlayer.Location = new Point(100, 200);
pbShot.Location = pbPlayer.Location;
}
private void MainGame_MouseMove_1(object sender, MouseEventArgs e)
{
var y2 = e.Y;
var y1 = (this.pbPlayer.Location.Y + (this.pbPlayer.Height / 2));
var x2 = e.X;
var x1 = (this.pbPlayer.Location.X + (this.pbPlayer.Width / 2));
var angle = (float)Math.Atan2((y1 - y2), (x1 - x2));
pbPlayer.Image = RotateImage(originalImage, (angle * 57));
}
private double Angle(Point start, Point end)
{
return (float)Math.Atan2(end.Y - start.Y, end.X - start.X) * 57;
}
private void timer2_Tick_1(object sender, EventArgs e)
{
nextStart.X -= Convert.ToInt16(interval * ((float)Math.Cos(radian / Rad2Grad)));
nextStart.Y -= Convert.ToInt16(interval * ((float)Math.Sin(radian / Rad2Grad)));
pbShot.Location = nextStart;
}
public static Image RotateImage(Image img, float rotationAngle)
{
Bitmap bmp = new Bitmap(img.Width, img.Height);
Graphics gfx = Graphics.FromImage(bmp);
gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2);
gfx.RotateTransform(rotationAngle);
gfx.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2);
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfx.DrawImage(img, new Point(0, 0));
gfx.Dispose();
return bmp;
}
private void MovePlayer()
{
if (pRight == true && pbPlayer.Left < 900)
{
pbPlayer.Left += pSpeed;
}
else if (pLeft == true && pbPlayer.Left > 0)
{
pbPlayer.Left -= pSpeed;
}
else if (pUp == true && pbPlayer.Top < 600)
{
pbPlayer.Top += pSpeed;
}
else if (pDown == true && pbPlayer.Top > 0)
{
pbPlayer.Top -= pSpeed;
}
}
The expected outcome is for the movement, aiming and firing to work as intended within the groupboxes but currently they do not execute in the code while in the groupboxes. It works fine in the form but not in the groupboxes. I would appriciate any help.

Related

Mp3 player lags after selecting a song (c#)

After selecting a song in filedrop, the player freezes for a while and then postpones
When re-selecting a song, the player behaves the same
The delay time is about 10 seconds, after which the player works normally again.
The problem is connected with a file drop, or with button 3, when the player starts playing music
Code:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using WMPLib;
namespace Music_Player
{
public partial class Form1 : Form
{
private WMPLib.WindowsMediaPlayer Player;
private Image pauseImage;
private Image playImage;
private bool isPlaying;
public Form1()
{
InitializeComponent();
button3.ImageAlign = ContentAlignment.MiddleCenter;
}
private void Form1_Load(object sender, EventArgs e)
{
Player = new WMPLib.WindowsMediaPlayer();
Player.PlayStateChange += new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange);
Player.MediaError += new WMPLib._WMPOCXEvents_MediaErrorEventHandler(Player_MediaError);
string startPath = Application.StartupPath;
pauseImage = Image.FromFile(Path.Combine(startPath, "pause.png"));
playImage = Image.FromFile(Path.Combine(startPath, "play.png"));
button3.Image = playImage;
}
private void Player_PlayStateChange(int newState)
{
isPlaying = (WMPLib.WMPPlayState)newState == WMPLib.WMPPlayState.wmppsPlaying;
if (isPlaying)
button3.Image = pauseImage;
else
button3.Image = playImage;
}
private void Player_MediaError(object pMediaObject)
{
MessageBox.Show($"Cannot play media file {Player.URL}.");
}
private void button3_Click(object sender, EventArgs e)
{
if (isPlaying)
{
hScrollBar1.Enabled = true;
timer1.Enabled = true;
timer1.Interval = 1000;
Player.controls.pause();
}
else
{
hScrollBar1.Enabled = true;
timer1.Enabled = true;
timer1.Interval = 1000;
Player.controls.play();
}
}
private void button5_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (isPlaying)
Player.controls.pause();
label5.Text = openFileDialog1.SafeFileName;
Player.URL = openFileDialog1.FileName;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
hScrollBar1.Maximum = Convert.ToInt32(Player.currentMedia.duration);
hScrollBar1.Value = Convert.ToInt32(Player.controls.currentPosition);
if (Player != null)
{
int s = (int)Player.currentMedia.duration;
int h = s / 3600;
int m = (s - (h * 3600)) / 60;
s = s - (h * 3600 + m * 60);
label3.Text = String.Format("{0:D}:{1:D2}:{2:D2}", h, m, s);
s = (int)Player.controls.currentPosition;
h = s / 3600;
m = (s - (h * 3600)) / 60;
s = s - (h * 3600 + m * 60);
label2.Text = String.Format("{0:D}:{1:D2}:{2:D2}", h, m, s);
}
else
{
label3.Text = "0:00:00";
label2.Text = "0:00:00";
}
}
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
Player.controls.currentPosition = hScrollBar1.Value;
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
if (trackBar1.Value == 10)
Player.settings.volume = 100;
if (trackBar1.Value == 9)
Player.settings.volume = 90;
if (trackBar1.Value == 8)
Player.settings.volume = 80;
if (trackBar1.Value == 7)
Player.settings.volume = 70;
if (trackBar1.Value == 6)
Player.settings.volume = 60;
if (trackBar1.Value == 5)
Player.settings.volume = 50;
if (trackBar1.Value == 4)
Player.settings.volume = 40;
if (trackBar1.Value == 3)
Player.settings.volume = 30;
if (trackBar1.Value == 2)
Player.settings.volume = 20;
if (trackBar1.Value == 1)
Player.settings.volume = 10;
if (trackBar1.Value == 0)
Player.settings.volume = 0;
}
}
}

How to move and change the size of shapes using mouse in C#

I'm looking for the method for moving and changing the size of shape using mouse #C.
That shape made by mouse location (Point start, end) on pictureBox named "captureDesign".
I wanted to ask for a little bit of help.
I searched many similar case of question, but I couldn't solve it yet.
IF possible, please let me know to how.
Here is my code.
It's not everything, for example, I omitted the contents about the mode selection for shape using Button_click.
I studied the similar case.
But I haven't noticed it yet.
How can I associate startPt (#MouseDown) and endPt (#MouseUp) with MyMove to make the move successful?
MyMove code is written in upper link. I need it change.
Actually I need to code for change the size but, first of all, I want to move that using mouse.
namespace Pilot
{
enum DrawMode { LINE, RECTANGLE, CIRCLE, NUMBER };
public partial class mainForm : Form
{
#region define
private bool _isCaptionShow = false;
private ScreenPicture sp;
private IContainer components = null;
Bitmap bitmap;
private DrawMode drawMode;
private Graphics g;
private Pen pen = new Pen(Color.Red, 7);
Point startPt, endPt, currPt, prevPt, addPt;
private int numberCount = 0;
int rectWidth, rectHeight;
Font font = new Font("Arial", 12);
private bool selectMode = false;
private void selectModeButton_CheckedChanged(object sender, EventArgs e)
{
if (selectModeButton.Checked == true)
selectMode = true;
else
selectMode = false;
}
MyMove m;
Point deltaStart;
Point deltaEnd;
bool dragging = false;
#region Contents on PictureBox "captureDesign;" when mouse clicked.
private void captureDesign_MouseDown(object sender, MouseEventArgs e)
{
startPt = new Point(e.X, e.Y);
prevPt = startPt;
currPt = startPt;
if (selectMode)
{
if (e.Button == MouseButtons.Left && m.IsPointOnLine(e.Location, 5))
{
dragging = true;
deltaStart = new Point(startPt.X- e.Location.X, startPt.Y - e.Location.Y);
}
}
}
#region Contents on PictureBox captureDesign when Mouse dropped.
private void captureDesign_MouseUp(object sender, MouseEventArgs e)
{
g = captureDesign.CreateGraphics();
endPt = new Point(e.X, e.Y);
m = new MyMove(pen, startPt, endPt);
#region calculate between start Point ~ end Point to width, height
if (endPt.X < startPt.X)
{
rectWidth = Math.Abs(endPt.X - startPt.X);
addPt.X = endPt.X;
}
else
{
rectWidth = Math.Abs(endPt.X - startPt.X);
addPt.X = startPt.X;
}
if (endPt.Y < startPt.Y)
{
rectHeight = Math.Abs(endPt.Y - startPt.Y);
addPt.Y = endPt.Y;
}
else
{
rectHeight = Math.Abs(endPt.Y - startPt.Y);
addPt.Y = startPt.Y;
}
#endregion
if (selectMode)
{
deltaEnd = new Point(endPt.X - e.Location.X, endPt.Y - e.Location.Y);
}
else //No selectMode
{
#region draw the shape in case of drawMode
switch (drawMode)
{
case DrawMode.LINE:
if (arrowCheck.Checked == true)
{
pen.StartCap = LineCap.ArrowAnchor;
}
else
//g.DrawLine(pen, startPt, endPt);
g.DrawLine(m.mpen, m.mStart, m.mEnd);
break;
case DrawMode.RECTANGLE:
//g.DrawRectangle(pen, new Rectangle(startPt, new Size(endPt.X - startPt.X, endPt.Y - startPt.Y)));
g.DrawRectangle(pen, new Rectangle(addPt, new Size(rectWidth, rectHeight)));
break;
case DrawMode.CIRCLE:
g.DrawEllipse(pen, new Rectangle(addPt, new Size(rectWidth, rectHeight)));
break;
case DrawMode.NUMBER:
numberCount++;
g.DrawString(numberCount.ToString(), font, Brushes.White, endPt);
break;
}
#endregion
}
}
#region
private void captureDesign_MouseMove(object sender, MouseEventArgs e)
{
if (dragging && deltaStart != null && deltaEnd != null)
{
m.mStart = new Point(deltaStart.X + e.Location.X, deltaStart.Y + e.Location.Y);
m.mEnd = new Point(deltaEnd.X + e.Location.X, deltaEnd.Y + e.Location.Y);
}
}
}
public class MyMove
{
public Pen mpen { get; set; }
public Point mStart { get; set; }
public Point mEnd { get; set; }
public MyMove(Pen p, Point p1, Point p2)
{
mpen = p;
mStart = p1;
mEnd = p2;
}
public float slope
{
get
{
return (((float)mEnd.Y - (float)mStart.Y) / ((float)mEnd.X - (float)mStart.X));
}
}
public float YIntercept
{
get
{
return mStart.Y - slope * mStart.X;
}
}
public bool IsPointOnLine(Point p, int cushion)
{
float temp = (slope * p.X + YIntercept);
if (temp >= (p.Y-cushion) && temp <=(p.Y+cushion))
{
return true;
}
else
{
return false;
}
}
}
1ST ANSWER
Everything happens on MouseMove(object sender, MouseEventArgs e).
Here is a sample
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
//If we are not allowed to draw, simply return and disregard the rest of the code
if (!_canDraw) return;
//The x-value of our rectangle should be the minimum between the start x-value and the current x-position
int x = Math.Min(_startX, e.X);
//The y-value of our rectangle should also be the minimum between the start y-value and current y-value
int y = Math.Min(_startY, e.Y);
//The width of our rectangle should be the maximum between the start x-position and current x-position minus
//the minimum of start x-position and current x-position
int width = Math.Max(_startX, e.X) - Math.Min(_startX, e.X);
//For the hight value, it's basically the same thing as above, but now with the y-values:
int height = Math.Max(_startY, e.Y) - Math.Min(_startY, e.Y);
_rect = new Rectangle(x, y, width, height);
//Refresh the form and draw the rectangle
Refresh();
}
protected override void OnPaint(PaintEventArgs e)
{
//Create a new 'pen' to draw our rectangle with, give it the color red and a width of 2
using (Pen pen = new Pen(Color.Red, 2))
{
//Draw the rectangle on our form with the pen
e.Graphics.DrawRectangle(pen, _rect);
}
}
You can further study the detail here, C# Tutorial - Drawing rectangles with the mouse.
2ND ANSWER (UPDATE)
I achieve the solution you want but I use a third party library MoveGraphLibrary. You can further read this article Moveable Resizable Objects.
Sample Code
GRAPHICAL OBJECT
public class Rectangle : GraphicalObject
{
protected RectangleF rc;
protected Resizing resize;
protected float wMin, wMax, hMin, hMax;
protected int radius;
protected int halfstrip;
protected SolidBrush brush;
int minsize = 25;
// -------------------------------------------------
public Rectangle(RectangleF rect, RectRange range, int rad, int half, Color color)
{
rc = new RectangleF(rect.X, rect.Y, Math.Max(minsize, rect.Width), Math.Max(minsize, rect.Height));
if (range == null)
{
wMin = wMax = rc.Width;
hMin = hMax = rc.Height;
}
else
{
wMin = Math.Max(minsize, Math.Min(rc.Width, range.MinWidth));
wMax = Math.Max(rc.Width, range.MaxWidth);
hMin = Math.Max(minsize, Math.Min(rc.Height, range.MinHeight));
hMax = Math.Max(rc.Height, range.MaxHeight);
}
RectRange realrange = new RectRange(wMin, wMax, hMin, hMax);
resize = realrange.Resizing;
radius = rad;
halfstrip = half;
brush = new SolidBrush(color);
}
// -------------------------------------------------
// ------------------------------------------------- RectAround
new public RectangleF RectAround
{
get { return (rc); }
}
// ------------------------------------------------- Radius
public int Radius
{
get { return (radius); }
set
{
radius = Math.Abs(value);
DefineCover();
}
}
// ------------------------------------------------- HalfStrip
public int HalfStrip
{
get { return (halfstrip); }
set
{
halfstrip = Math.Abs(value);
DefineCover();
}
}
// ------------------------------------------------- Color
public Color Color
{
get { return (brush.Color); }
set { brush.Color = value; }
}
// -------------------------------------------------
public void Draw(Graphics grfx)
{
grfx.FillRectangle(brush, rc);
}
// ------------------------------------------------- Resizing
public Resizing Resizing
{
get { return (resize); }
set
{
resize = value;
DefineCover();
}
}
// ------------------------------------------------- DefineCover
public override void DefineCover()
{
cover = new Cover(rc, resize, radius, halfstrip);
}
// -------------------------------------------------
public override void Move(int dx, int dy)
{
rc.X += dx;
rc.Y += dy;
}
// ------------------------------------------------- MoveNode
public override bool MoveNode(int iNode, int dx, int dy, Point ptM, MouseButtons catcher)
{
bool bRet = false;
if (catcher == MouseButtons.Left)
{
float wNew, hNew;
switch (resize)
{
case Resizing.Any:
if (iNode == 8)
{
Move(dx, dy);
}
else if (iNode == 0) //LT corner
{
hNew = rc.Height - dy;
if (hMin <= hNew && hNew <= hMax)
{
MoveBorder_Top(dy);
bRet = true;
}
wNew = rc.Width - dx;
if (wMin <= wNew && wNew <= wMax)
{
MoveBorder_Left(dx);
bRet = true;
}
}
else if (iNode == 1) // RT corner
{
hNew = rc.Height - dy;
if (hMin <= hNew && hNew <= hMax)
{
MoveBorder_Top(dy);
bRet = true;
}
wNew = rc.Width + dx;
if (wMin <= wNew && wNew <= wMax)
{
MoveBorder_Right(dx);
bRet = true;
}
}
else if (iNode == 2) // RB corner
{
wNew = rc.Width + dx;
if (wMin <= wNew && wNew <= wMax)
{
MoveBorder_Right(dx);
bRet = true;
}
hNew = rc.Height + dy;
if (hMin <= hNew && hNew <= hMax)
{
MoveBorder_Bottom(dy);
bRet = true;
}
}
else if (iNode == 3) // LB corner
{
hNew = rc.Height + dy;
if (hMin <= hNew && hNew <= hMax)
{
MoveBorder_Bottom(dy);
bRet = true;
}
wNew = rc.Width - dx;
if (wMin <= wNew && wNew <= wMax)
{
MoveBorder_Left(dx);
bRet = true;
}
}
else if (iNode == 4) // on left side
{
wNew = rc.Width - dx;
if (wMin <= wNew && wNew <= wMax)
{
MoveBorder_Left(dx);
bRet = true;
}
}
else if (iNode == 5) // on right side
{
wNew = rc.Width + dx;
if (wMin <= wNew && wNew <= wMax)
{
MoveBorder_Right(dx);
bRet = true;
}
}
else if (iNode == 6) // on top
{
hNew = rc.Height - dy;
if (hMin <= hNew && hNew <= hMax)
{
MoveBorder_Top(dy);
bRet = true;
}
}
else if (iNode == 7) // on bottom
{
hNew = rc.Height + dy;
if (hMin <= hNew && hNew <= hMax)
{
MoveBorder_Bottom(dy);
bRet = true;
}
}
break;
case Resizing.NS:
if (iNode == 2)
{
Move(dx, dy);
}
else if (iNode == 0) // on top
{
hNew = rc.Height - dy;
if (hMin <= hNew && hNew <= hMax)
{
MoveBorder_Top(dy);
bRet = true;
}
}
else if (iNode == 1) // on bottom
{
hNew = rc.Height + dy;
if (hMin <= hNew && hNew <= hMax)
{
MoveBorder_Bottom(dy);
bRet = true;
}
}
break;
case Resizing.WE:
if (iNode == 2)
{
Move(dx, dy);
}
else if (iNode == 0) // on left side
{
wNew = rc.Width - dx;
if (wMin <= wNew && wNew <= wMax)
{
MoveBorder_Left(dx);
bRet = true;
}
}
else if (iNode == 1) // on right side
{
wNew = rc.Width + dx;
if (wMin <= wNew && wNew <= wMax)
{
MoveBorder_Right(dx);
bRet = true;
}
}
break;
case Resizing.None:
Move(dx, dy);
break;
}
}
return (bRet);
}
// ------------------------------------------------- MoveBorder_Top
private void MoveBorder_Top(int dy)
{
rc.Y += dy;
rc.Height -= dy;
}
// ------------------------------------------------- MoveBorder_Bottom
private void MoveBorder_Bottom(int dy)
{
rc.Height += dy;
}
// ------------------------------------------------- MoveBorder_Left
private void MoveBorder_Left(int dx)
{
rc.X += dx;
rc.Width -= dx;
}
// ------------------------------------------------- MoveBorder_Right
private void MoveBorder_Right(int dx)
{
rc.Width += dx;
}
public PointF Location
{
get
{
return rc.Location;
}
}
}
MAIN FORM
public partial class Form1 : Form
{
RectRange rr;
// Variables use for Moving & Resizing
NumericUpDown numericUD_Radius = new NumericUpDown();
NumericUpDown numericUD_HalfStrip = new NumericUpDown();
string[] strs = new string[] {"Circles' radius",
"Half strip width"
};
Mover mover;
Point ptMouse_Down;
bool bShowCovers = false;
RigidlyBoundRectangles rigidrectsView;
List<Shapes.Rectangle> rects = new List<Shapes.Rectangle>();
int radius, halfstrip;
// Variables use for Drawing
bool isMouseDown = false;
public Form1()
{
InitializeComponent();
lblXAxis.Text = $"X Axis: -";
lblYAxis.Text = $"Y Axis: -";
numericUD_Radius.Value = 6;
numericUD_HalfStrip.Value = 3;
mover = new Mover(panel1);
SizeF[] sizefStrs = Auxi_Geometry.MeasureStrings(this, strs);
rigidrectsView = new RigidlyBoundRectangles(new Control[] { numericUD_Radius, numericUD_HalfStrip });
rigidrectsView.Add(Auxi_Geometry.RectangleToRectangleSide(numericUD_Radius.Bounds, Side.E, sizefStrs[0], 4), "Radius");
rigidrectsView.Add(Auxi_Geometry.RectangleToRectangleSide(numericUD_HalfStrip.Bounds, Side.E, sizefStrs[1], 4), "Strip");
rigidrectsView.AddUnionRectangle();
radius = Convert.ToInt32(numericUD_Radius.Value);
halfstrip = Convert.ToInt32(numericUD_HalfStrip.Value);
rr = new RectRange(panel1.MinimumSize.Width, panel1.Size.Width, panel1.MinimumSize.Height, panel1.Size.Height);
rects.Add(new Shapes.Rectangle(new RectangleF(100, 100, 300, 400), rr, radius, halfstrip, Color.Black));
RenewMover();
}
private void RenewMover()
{
mover.Clear();
mover.Insert(0, rigidrectsView);
for (int i = 0; i < rects.Count; i++)
{
mover.Add(rects[i]);
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics grfx = e.Graphics;
GraphicalObject grobj;
for (int i = mover.Count - 1; i >= 0; i--)
{
grobj = mover[i].Source;
if (grobj is Shapes.Rectangle)
{
(grobj as Shapes.Rectangle).Draw(grfx);
}
if (bShowCovers)
{
mover[i].DrawCover(grfx);
}
}
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
lblXAxis.Text = $"X Axis: {e.X}";
lblYAxis.Text = $"Y Axis: {e.Y}";
if (rbMoveOrResize.Checked && mover.Move(e.Location))
{
panel1.Invalidate();
}
else
{
if (isMouseDown)
{
var rectangle = rects.Last();
var drawRectangle = new Shapes.Rectangle(new RectangleF(rectangle.Location.X,
rectangle.Location.Y,
e.X - rectangle.Location.X,
e.Y - rectangle.Location.Y),
rr, radius, halfstrip, Color.Black);
rects.Remove(rects.Last());
rects.Add(drawRectangle);
RenewMover();
panel1.Invalidate();
}
}
}
private void panel1_MouseLeave(object sender, EventArgs e)
{
lblXAxis.Text = $"X Axis: -";
lblYAxis.Text = $"Y Axis: -";
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
if (rbMoveOrResize.Checked)
{
ptMouse_Down = e.Location;
mover.Catch(e.Location, e.Button);
}
else
{
isMouseDown = true;
rects.Add(new Shapes.Rectangle(new RectangleF(e.Location.X, e.Location.Y, 0, 0), rr, radius, halfstrip, Color.Black));
}
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
if (rbMoveOrResize.Checked && mover.Release())
{
if (e.Button == MouseButtons.Left &&
Auxi_Geometry.Distance(ptMouse_Down, e.Location) <= 3)
{
GraphicalObject grobj = mover[mover.ReleasedObject].Source;
if (grobj is Shapes.Rectangle)
{
PopupRectangle(grobj.ID);
}
}
}
else
{
isMouseDown = false;
}
}
private void rb_CheckedChanged(object sender, EventArgs e)
{
bShowCovers = rbMoveOrResize.Checked;
panel1.Invalidate();
}
private void PopupRectangle(long id)
{
for (int i = rects.Count - 1; i > 0; i--)
{
if (id == rects[i].ID)
{
Shapes.Rectangle elem = rects[i];
rects.RemoveAt(i);
rects.Insert(0, elem);
RenewMover();
panel1.Invalidate();
break;
}
}
}
}
SAMPLE OUTPUT

C# - "Pong Game" - Collision with edges of paddle

I dont know how to make ball bounce when hits Paddle´s Top or Bottom, my problem is that the ball goes through the Paddle and then keep going...
So this is the code, some things are in my language so here is translator:
Mustek = Paddle
Mic = Ball
body = Points
HraciPole = Name for graphics array, something like "GameArray"
casovac = name for timer
Kolize = Collision
PohybDolu = MoveUp (bool)
PohybNahoru = MoveDown (bool)
public partial class Form_Pong : Form
{
public static Mustek p1 = new Mustek();
public static Mustek p2 = new Mustek();
public static Mic ball = new Mic();
public int body1 = 0;
public int body2 = 0;
Graphics draw;
public Form_Pong()
{
InitializeComponent();
draw = picBoxHraciPole.CreateGraphics();
}
public static void Draw(Graphics draw)
{
draw.Clear(Color.Black);
draw.FillRectangle(new SolidBrush(Color.Blue), new Rectangle(p1.location, p1.size));
draw.FillRectangle(new SolidBrush(Color.Red), new Rectangle(p2.location, p2.size));
draw.FillRectangle(new SolidBrush(Color.White), new Rectangle(ball.location, ball.size));
}
private void casovac_Tick(object sender, EventArgs e)
{
if (casovac.Interval == 10)
{
p1.location.X = 30;
p1.location.Y = (picBoxHraciPole.Height - p1.size.Height) / 2;
p2.location.X = (picBoxHraciPole.Width - p2.size.Width) - 30;
p2.location.Y = p1.location.Y;
ball.location = new Point(picBoxHraciPole.Width / 2, picBoxHraciPole.Height / 2);
casovac.Interval = 5;
}
Kolize();
Pohyb();
Draw(draw);
}
public void Kolize()
{
if (p1.location.Y < 0)
{
p1.location.Y = 0;
}
if (p1.location.Y + p1.size.Height > picBoxHraciPole.Height)
{
p1.location.Y = picBoxHraciPole.Height - p1.size.Height;
}
if (p2.location.Y < 0)
{
p2.location.Y = 0;
}
if (p2.location.Y + p2.size.Height > picBoxHraciPole.Height)
{
p2.location.Y = picBoxHraciPole.Height - p2.size.Height;
}
if (ball.location.Y < 0)
{
ball.speed.Y = -ball.speed.Y;
}
if (ball.location.Y + ball.size.Height > picBoxHraciPole.Height)
{
ball.speed.Y = -ball.speed.Y;
}
if (ball.location.X < 0)
{
body2 += 1;
labelBody2.Text = body2.ToString();
Reset();
}
if (ball.location.X + ball.size.Width > picBoxHraciPole.Width)
{
body1 +=1;
labelBody1.Text = body1.ToString();
Reset();
}
if (new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p1.location, p1.size)) ||
new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p2.location, p2.size)))
{
ball.speed.X = -ball.speed.X;
}
if (new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p1.location, p1.size)) ||
new Rectangle(ball.location, ball.size).IntersectsWith(new Rectangle(p2.location, p2.size)))
{
}
}
public void Reset()
{
ball.location = new Point(picBoxHraciPole.Width / 2, picBoxHraciPole.Height / 2);
ball.speed.X = -ball.speed.X;
ball.speed.Y = -ball.speed.Y;
}
public static void Pohyb()
{
if (p1.PohybNahoru == true)
{
p1.location.Y -= 8;
}
if (p1.PohybDolu == true)
{
p1.location.Y += 6;
}
if (p2.PohybNahoru == true)
{
p2.location.Y -= 6;
}
if (p2.PohybDolu == true)
{
p2.location.Y += 6;
}
ball.location.X += ball.speed.X;
ball.location.Y += ball.speed.Y;
}
private void Form_Pong_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
p1.PohybNahoru = true;
}
if (e.KeyCode == Keys.S)
{
p1.PohybDolu = true;
}
if (e.KeyCode == Keys.Escape)
{
Application.Exit();
}
if (e.KeyCode == Keys.Up)
{
p2.PohybNahoru = true;
}
if (e.KeyCode == Keys.Down)
{
p2.PohybDolu = true;
}
if (e.KeyCode == Keys.F1)
{
casovac.Enabled = false;
}
if (e.KeyCode == Keys.F2)
{
casovac.Enabled = true;
}
}
private void EnableDoubleBuffering()
{
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
}
private void Form_Pong_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
p1.PohybNahoru = false;
}
if (e.KeyCode == Keys.S)
{
p1.PohybDolu = false;
}
if (e.KeyCode == Keys.Up)
{
p2.PohybNahoru = false;
}
if (e.KeyCode == Keys.Down)
{
p2.PohybDolu = false;
}
}
}
public class Mustek
{
public Point location;
public Size size;
public bool PohybNahoru, PohybDolu;
public int Score;
public Mustek()
{
Score = 0;
size.Width = 25;
size.Height = 125;
}
}
public class Mic
{
public Point location;
public Size size;
public Point speed;
public Mic()
{
speed.X = -5;
speed.Y = 5;
this.size.Width = 25;
this.size.Height = 25;
}
}
The basic logic that you are looking for is
If edge of ball =edge of paddle then change direction so as if x was decreasing bow x is to ve increasing
Once you have that you can work out angles for different conditions such as if it gits the edge of the paddle ect.

C# Keep picturebox in form1

I have a picturebox in windows form application that has the ability to move with arrowkeys. I want it to have certain limits to where it can go, specifically in the form. How do I do this? My class to move the target is below:
namespace AmazingPaintball
{
class Target
{
private Point p;
public Target(Point myPoi)
{
p = myPoi;
}
public Point Move(Keys key)
{
if (key == Keys.Left)
{
p.Offset(-50, 0);
}
else if (key == Keys.Right)
{
p.Offset(50, 0);
}
else if (key == Keys.Up)
{
p.Offset(0, -50);
}
else if (key == Keys.Down)
{
p.Offset(0, 50);
}
return p;
}
}
}
Below is the form1:
namespace AmazingPaintball
{
public partial class Form1 : Form
{
Random positionX = new Random();
Random positionY = new Random();
Target einstein;
int count = 0;
Paintballs pBalls = new Paintballs();
Stopwatch stopwatch = new Stopwatch();
SoundPlayer wavPlayer = new SoundPlayer(#"G:\ChefBrohansPaintballFunNew\ChefBrohansPaintballFun\Resources\singlegunshot.wav");
SoundPlayer wavPlayer2 = new SoundPlayer(#"G:\ChefBrohansPaintballFunNew\ChefBrohansPaintballFun\bin\Debug\Resources\Applause.wav");
public Form1()
{
InitializeComponent();
Point point = new Point(positionX.Next(0, 638), positionY.Next(0, 404));
einstein = new Target(point);
ptrEinstein.Location = point;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
pBalls.paint(e.Graphics);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
ptrEinstein.Location = einstein.Move(e.KeyData);
pictureBox1.Update();
pictureBox1.Refresh();
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
wavPlayer.Play();
pBalls.add(e.Location);
pictureBox1.Refresh();
count++;
}
private void Form1_Load(object sender, EventArgs e)
{
stopwatch.Start();
}
private void ptrEinstein_MouseClick(object sender, MouseEventArgs e)
{
count++;
ptrEinstein.Image = Properties.Resources.AlbertEinsteinTongue;
stopwatch.Stop();
wavPlayer2.Play();
MessageBox.Show("It took " + count + " shots and " + stopwatch.Elapsed + " seconds to hit the target");
wavPlayer2.Stop();
ptrEinstein.Image = Properties.Resources.AlbertEinsteinFace;
count = 0;
stopwatch.Reset();
stopwatch.Start();
}
}
}
The picturebox is ptrEinstein and it is able to move in the form1_keydown event.
When you're moving the picture box, first check to make sure where you're moving it to is inside the form. E.g. check if the new X + the width of the picture box is less than the width of the form, etc.
This will be incomplete because we do not have your code, but you should compare the clientSize properties to the picturebox location (taking into account the size of the picturebox):
PictureBox pb = new PictureBox();
int newX = oldX + xOffset; // xOffset is whatever you're incrementing x by
int newY = oldY + yOffset; // yOffset is whatever you're incrementing y by
if (newX < 0) {
newX = 0;
} else if (newX > this.ClientSize.Width - pb.Width) {
newX = this.ClientSize.Width - pb.Width;
}
if (newY < 0) {
newY = 0;
} else if (newY > this.ClientSize.Height - pb.Height) {
newY = this.ClientSize.Height - pb.Height;
}
// New point to move it to
Point newP = new Point(newX, newY);

How to test if a window is being dragged C# WPF

I have a title-less window, as I wanted to create a window style of my own.
The title and minimize, maximize and close buttons are in a dock panel. I have added the following event handler to maximize, restore and drag the window.
The problem comes when the window is maximized.
What I have found is that whenever I do a single click on the title is restores. When I only want it to restore if it is double clicked or dragged. I can see why it is happening but unsure how to resolve this.
public void TITLEBAR_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DockPanel dp = (DockPanel)sender;
Window parentWindow = Window.GetWindow(dp);
bool doubleClick = IsDoubleClick(sender, e);
if (e.ChangedButton == MouseButton.Left && e.LeftButton == MouseButtonState.Pressed && !doubleClick)
{
if (parentWindow.WindowState == WindowState.Maximized)
{
double mouseX = e.GetPosition(parentWindow).X;
double width = parentWindow.RestoreBounds.Width;
System.Drawing.Rectangle screenBounds = getCurrentScreenBounds(parentWindow);
double x = screenBounds.Left + (mouseX - ((width / 100.00) * ((100.00 / screenBounds.Width) * mouseX)));
if (x < 0)
{
x = 0;
}
else
{
if (x + width > screenBounds.Left + screenBounds.Width)
{
x = screenBounds.Left + screenBounds.Width - width;
}
}
parentWindow.Left = x;
parentWindow.Top = screenBounds.Top;
parentWindow.WindowState = System.Windows.WindowState.Normal;
}
parentWindow.DragMove();
//MessageBox.Show("");
}
if (doubleClick)
{
if (parentWindow.WindowState == System.Windows.WindowState.Maximized)
{
parentWindow.WindowState = System.Windows.WindowState.Normal;
}
else
{
parentWindow.WindowState = System.Windows.WindowState.Maximized;
}
}
}
Along with this class:
public static class MouseButtonHelper
{
private const long k_DoubleClickSpeed = 500;
private const double k_MaxMoveDistance = 10;
private static long _LastClickTicks = 0;
private static System.Windows.Point _LastPosition;
private static WeakReference _LastSender;
public static bool IsDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
System.Windows.Point position = e.GetPosition(null);
long clickTicks = DateTime.Now.Ticks;
long elapsedTicks = clickTicks - _LastClickTicks;
long elapsedTime = elapsedTicks / TimeSpan.TicksPerMillisecond;
bool quickClick = (elapsedTime <= k_DoubleClickSpeed);
bool senderMatch = (_LastSender != null && sender.Equals(_LastSender.Target));
if (senderMatch && quickClick && position.Distance(_LastPosition) <= k_MaxMoveDistance)
{
// Double click!
_LastClickTicks = 0;
_LastSender = null;
return true;
}
// Not a double click
_LastClickTicks = clickTicks;
_LastPosition = position;
if (!quickClick)
_LastSender = new WeakReference(sender);
return false;
}
private static double Distance(this System.Windows.Point pointA, System.Windows.Point pointB)
{
double x = pointA.X - pointB.X;
double y = pointA.Y - pointB.Y;
return Math.Sqrt(x * x + y * y);
}
}
And this to work out bounds of the current screen.
public static class WindowHelper
{
public static System.Drawing.Rectangle getCurrentScreenBounds(System.Windows.Window pWnd)
{
System.Windows.Forms.Screen parentScreen = GetCurrentScreen(pWnd);
if (parentScreen == null)
{
return System.Windows.Forms.Screen.PrimaryScreen.Bounds;
}
return parentScreen.Bounds;
}
private static System.Windows.Forms.Screen GetCurrentScreen(System.Windows.Window pWnd)
{
System.Drawing.Rectangle intersectingRect = new System.Drawing.Rectangle();
System.Drawing.Rectangle windowRect = new System.Drawing.Rectangle(Convert.ToInt32(pWnd.Left), Convert.ToInt32(pWnd.Top), Convert.ToInt32(pWnd.Width), Convert.ToInt32(pWnd.Height));
int largestIntersectingArea = 0;
System.Windows.Forms.Screen curScreen = null;
foreach (System.Windows.Forms.Screen s in System.Windows.Forms.Screen.AllScreens)
{
if (s.Bounds.IntersectsWith(windowRect))
{
intersectingRect = System.Drawing.Rectangle.Intersect(s.Bounds, windowRect);
int intersectingArea = intersectingRect.Width * intersectingRect.Height;
if (intersectingArea > largestIntersectingArea)
{
largestIntersectingArea = intersectingArea;
curScreen = s;
}
}
}
return curScreen;
}
}
There is a WPF element (control) named Thumb, I use that for making drag-able parts. It has a DragDelta event which you can use to examine HorizontalOffset and VerticalOffset of the drag-able part. You can save previous values and check if new values are the same or changed; which means it is being dragged.
(Just a suggestion which worked for me).
Ok so maybe someone will find this helpful.
I changed things around so that it recognizes the drag through two events, in the MouseMove and MouseLeftButtonDown events.
MouseLeftButtonDown captures a possible start position for drag in setStartPosition().
public void TITLEBAR_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DockPanel dp = (DockPanel)sender;
Window parentWindow = Window.GetWindow(dp);
doubleClick = IsDoubleClick(sender, e);
if (e.ChangedButton == MouseButton.Left && e.LeftButton == MouseButtonState.Pressed && !doubleClick)
{
if (parentWindow.WindowState == WindowState.Maximized)
{
setStartPosition(sender, e);
}
}
if (doubleClick)
{
if (parentWindow.WindowState == System.Windows.WindowState.Maximized)
{
parentWindow.WindowState = System.Windows.WindowState.Normal;
}
else
{
parentWindow.WindowState = System.Windows.WindowState.Maximized;
}
}
}
private void TITLEBAR_MouseMove(object sender, MouseEventArgs e)
{
DockPanel dp = (DockPanel)sender;
Window parentWindow = Window.GetWindow(dp);
if (e.LeftButton == MouseButtonState.Pressed)
{
if (IsDragging(sender, e) && !doubleClick)
{
if (parentWindow.WindowState == WindowState.Maximized)
{
double mouseX = e.GetPosition(parentWindow).X;
double width = parentWindow.RestoreBounds.Width;
System.Drawing.Rectangle screenBounds = getCurrentScreenBounds(parentWindow);
double x = screenBounds.Left + (mouseX - ((width / 100.00) * ((100.00 / screenBounds.Width) * mouseX)));
if (x < 0)
{
x = 0;
}
else
{
if (x + width > screenBounds.Left + screenBounds.Width)
{
x = screenBounds.Left + screenBounds.Width - width;
}
}
parentWindow.Left = x;
parentWindow.Top = screenBounds.Top;
parentWindow.WindowState = System.Windows.WindowState.Normal;
}
parentWindow.DragMove();
}
}
}
Here is the modified class:
public static class MouseButtonHelper
{
private const long k_DoubleClickSpeed = 500;
private const double k_MaxMoveDistance = 10;
private static long _LastClickTicks = 0;
private static System.Windows.Point _LastPosition;
private static WeakReference _LastSender;
private static System.Windows.Point _DragStartPosition;
public static bool IsDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
System.Windows.Point position = e.GetPosition(null);
long clickTicks = DateTime.Now.Ticks;
long elapsedTicks = clickTicks - _LastClickTicks;
long elapsedTime = elapsedTicks / TimeSpan.TicksPerMillisecond;
bool quickClick = (elapsedTime <= k_DoubleClickSpeed);
bool senderMatch = (_LastSender != null && sender.Equals(_LastSender.Target));
if (senderMatch && quickClick && position.Distance(_LastPosition) <= k_MaxMoveDistance)
{
// Double click!
_LastClickTicks = 0;
_LastSender = null;
return true;
}
// Not a double click
_LastClickTicks = clickTicks;
_LastPosition = position;
if (!quickClick)
_LastSender = new WeakReference(sender);
return false;
}
public static void setStartPosition(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
_DragStartPosition = e.GetPosition(null);
}
public static bool IsDragging(object sender, System.Windows.Input.MouseEventArgs e)
{
System.Windows.Point mousePos = e.GetPosition(null);
System.Windows.Vector diff = _DragStartPosition - mousePos;
if (Math.Abs(diff.X) > System.Windows.SystemParameters.MinimumHorizontalDragDistance || Math.Abs(diff.Y) > System.Windows.SystemParameters.MinimumVerticalDragDistance)
{
return true;
}
return false;
}
private static double Distance(this System.Windows.Point pointA, System.Windows.Point pointB)
{
double x = pointA.X - pointB.X;
double y = pointA.Y - pointB.Y;
return Math.Sqrt(x * x + y * y);
}
}

Categories

Resources