I'm creating a simple bouncing ball application that uses a timer to bounce the ball of the sides of a picture box, the trouble i'm having with this is that it bounces fine off the bottom and right side of the picture box but doesn't bounce off the top or left side and i'm not sure why, the ball size is 30 if you wanted to know
The code for it is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace Ball
{
public partial class Form1 : Form
{
int x = 200, y = 50; // start position of ball
int xmove = 10, ymove = 10; // amount of movement for each tick
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void pbxDisplay_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics; // get a graphics object
// draw a red ball, size 30, at x, y position
g.FillEllipse(Brushes.Red, x, y, 30, 30);
}
private void timer1_Tick(object sender, EventArgs e)
{
x += xmove; // add 10 to x and y positions
y += ymove;
if(y + 30 >= pbxDisplay.Height)
{
ymove = -ymove;
}
if (x + 30 >= pbxDisplay.Width)
{
xmove = -xmove;
}
if (x - 30 >= pbxDisplay.Width)
{
xmove = -xmove;
}
if (y - 30 >= pbxDisplay.Height)
{
ymove = -ymove;
}
Refresh(); // refresh the`screen .. calling Paint() again
}
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Enabled= false;
}
}
}
If anyone can see what my problem is then please let me know, thanks alot!
Well your method for edge recognition is wrong. Top left corner point got coordinates [0,0]. So you should check left and top against zero. Not Width and Height.
So your code should look like:
private void timer1_Tick(object sender, EventArgs e)
{
x += xmove; // add 10 to x and y positions
y += ymove;
if(y + 30 >= pbxDisplay.Height)
{
ymove = -ymove;
}
if (x + 30 >= pbxDisplay.Width)
{
xmove = -xmove;
}
if (x - 30 <= 0)
{
xmove = -xmove;
}
if (y - 30 <= 0)
{
ymove = -ymove;
}
Refresh(); // refresh the`screen .. calling Paint() again
}
Related
My question is very simple.
My Label1 should move continuously from left to right.
(Start from the left part of the form and go to the right part of the form. When it reaches the right part of the Form, go to the left and so on.) I have 2 timers(one for right and one for left)
I have the following code, it starts at the left and goes to the right, but when it reaches the right of the Form, it doesn't return.
Can anyone help me?
enum Position
{
Left,Right
}
System.Windows.Forms.Timer timerfirst = new System.Windows.Forms.Timer();
private int _x;
private int _y;
private Position _objPosition;
public Form1()
{
InitializeComponent();
if (label1.Location == new Point(0,180))
{
_objPosition = Position.Right;
}
if (label1.Location == new Point(690,0))
{
_objPosition = Position.Left;
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Label1.SetBounds(_x, _y, 0, 180);
}
private void tmrMoving_Tick(object sender, EventArgs e)
{
tmrMoving.Start();
if (_objPosition == Position.Right && _x < 710)
{
_x +=10;
}
if(_x == 710)
{
tmrMoving.Stop();
}
Invalidate();
}
private void tmrMoving2_Tick(object sender, EventArgs e)
{
tmrMoving2.Start();
if (_objPosition == Position.Right && _x > 690)
{
_x -= 10;
}
if(_x == 1)
{
tmrMoving2.Stop();
}
Invalidate();
}
Thanks.
I think you've overcomplicated things. Let's just have one timer, a step number of pixels that we sometimes flip negative, and some time later flip back to positive. We can move the label by repeatedly setting its Left:
public partial class Form1 : Form
{
private int _step = 10;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (label1.Right > this.Width) _step = -10;
if (label1.Left < 0) _step = 10;
label1.Left += _step;
}
}
You might want to fine tune it, but the basic motion is there
I am trying to create a game in Visual studios using C# where you have rows of sliding boxes that you must press a key in certain locations one after the other, kinda like stacker, before the time runs out.
I am using this as the basis but unsure how to adjust the speed among making it work in the first place since the code apparently runs with no issues but I only got it where the button just gives you a message box.
https://www.youtube.com/watch?v=O78n7apXjG8
Just asking for tips on where to go.
https://files.catbox.moe/x3wx22.zip
additional info for clarification
https://catbox.moe/c/fakpxe
// Project by 124
// Redid:
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 WinFormsApp1
{
public partial class Form1 : Form
{
private int _ticks;
private object textBox1;
public Form1()
{
InitializeComponent();
timer1.Start();
}
//This should be the part that moves the button back and forth but it's not working
int Left = 140;
private void timer1_tick(object sender, EventArgs e)
{
Left += 10;
if (Left > 430)
{
Left = -138;
Left += Left;
if (Left > 140 )
{
} else
{
button1.Left = Left;
}
}
else
button1.Left = Left;
{
button1.Visible = false;
button2.Visible = true;
}
{
_ticks++;
this.Text = _ticks.ToString();
if (_ticks == 9)
{
this.Text = "Game Over";
timer1.Stop();
}
}
}
private void button1_Click(object sender, EventArgs e)
//since the movement button function is not working so is this one where it's supposed to give you the win but the win is there regardless
{
if (_ticks < 9) ;
{
MessageBox.Show("good job you beat the time");
MessageBox.Show("You are a winner");
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Restart();
Environment.Exit(0);
}
private void button3_Click(object sender, EventArgs e)
{
Form3 f3 = new Form3();
f3.ShowDialog();
}
}
}
Adjust the speed among making it work:
Left += Convert.ToInt32(label1.Text);
Control speed +1:
private void Button4_Click(object sender, EventArgs e) {
label1.Text = (Convert.ToInt32(label1.Text) + 1).ToString();
}
Control speed -1:
private void Button5_Click(object sender, EventArgs e) {
label1.Text = (Convert.ToInt32(label1.Text) - 1).ToString();
}
Updated:
Write at the top:
You can control the speed and position of the button by modifying the values of'V0' and'a'.
//current position
Left += 20* _ticks+(a* _ticks* _ticks)/2;//s = v0·t + a·t²/2
Set the initial time value outside the timer
private double _ticks = 0;
Set the initial position to 0.
double Left = 0;
Increase by 1 every second. Because internal is 0.2, add 0.2 every time.
_ticks+=0.2;
Modified timer1_tick:
private void timer1_tick(object sender, EventArgs e) {
//Set acceleration
double a = 0.5;
//Increase by 1 every second. Because internal is 0.2, add 0.2 every time.
_ticks += 0.2;
this.Text = _ticks.ToString();
//Time to stop at 9s
if (_ticks == 9) {
this.Text = "Game Over";
timer1.Stop();
MessageBox.Show("Game Over");
button1.Visible = false;
button2.Visible = true;
}
//current position
Left += 20 * _ticks + (a * _ticks * _ticks) / 2;//s = v0·t + a·t²/2
//When the total distance exceeds the set width on the interface, perform operations such as subtraction until the current position is less than the set value.
rtn:
if (Left > 300) {
Left -= 300;
if (Left > 300) {
goto rtn;//Use goto: Perform an iterative operation.
} else {
button1.Left = Convert.ToInt32(Left);//Cast double data type to int
}
} else
button1.Left = Convert.ToInt32(Left);
}
Modified button_Click: Don’t add ‘;’ after ‘if’, it will be useless.
private void button1_Click(object sender, EventArgs e) {
if (_ticks < 9) //Don’t add ‘;’ after ‘if’, it will be useless.
{
timer1.Stop();
button1.Visible = false;
button2.Visible = true;
MessageBox.Show("good job you beat the time");
MessageBox.Show("You are a winner");
}
}
Output:
I want to make an AI using PictureBox that can roam randomly without messing its movements like for example:
PictureBox must execute the movement to go Right, if the Timer runs out it the next movement is going Down, like just how random it would roam.
I'd thought I might figured it out to Hard code it. However might took long, also once the Timer Stops, it won't Restart again. idk why.
Here's a Picture of my Game so you would have some ideas about it.
Here's the code also
private void Game_Load(object sender, EventArgs e)
{
E_Right.Start();
if(Upcount == 0)
{
E_Right.Start();
}
}
private void E_Right_Tick(object sender, EventArgs e)
{
if(Rightcount > 0)
{
EnemyTank.Left += 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_RIGHT_v_2;
Rightcount = Rightcount - 1;
}
if (Rightcount == 0)
{
E_Right.Stop();
E_Down.Start();
}
}
private void E_Up_Tick(object sender, EventArgs e)
{
if (Upcount > 0)
{
EnemyTank.Top -= 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_TOP_v_1;
Upcount = Upcount - 1;
}
if (Upcount == 0)
{
E_Up.Stop();
E_Right.Start();
}
}
private void E_Down_Tick(object sender, EventArgs e)
{
if (Downcount > 0)
{
EnemyTank.Top += 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_DOWN_v_1;
Downcount = Downcount - 1;
}
if (Downcount == 0)
{
E_Down.Stop();
E_Left.Start();
}
}
private void E_Left_Tick(object sender, EventArgs e)
{
if (Leftcount > 0)
{
EnemyTank.Left -= 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_LEFT_v_1;
Leftcount = Leftcount - 1;
}
if (Leftcount == 0)
{
E_Left.Stop();
E_Up.Start();
}
}
Well just assume that the PictureBox is in Location(0,0). If you see a PictureBox an image of a Tank nevermind that. That goes for the MainTank of the user will be using.
You could do it with just one timer:
int moveTo = 0; // Move while this is not 0
int speed = 3;
Random rand = new Random();
// Keep track of whether the tank is moving up/down or left/right
enum MoveOrientation { Vertical, Horizontal };
MoveOrientation orientation = MoveOrientation.Vertical;
void ChooseNextPosition()
{
// Negative numbers move left or down
// Positive move right or up
do {
moveTo = rand.Next(-5, 5);
} while (moveTo == 0); // Avoid 0
}
private void Game_Load(object sender, EventArgs e) {
ChooseNextPosition();
timer1.Start();
}
private void timer1Tick(object sender, EventArgs e) {
if (orientation == MoveOrientation.Horizontal)
{
EnemyTank.Left += moveTo * speed;
}
else
{
EnemyTank.Top += moveTo * speed;
}
moveTo -= moveTo < 0 ? -1 : 1;
if (moveTo == 0)
{
// Switch orientation.
// If currently moving horizontal, next move is vertical
// And vice versa
orientation = orientation == MoveOrientation.Horizontal ? MoveOrientation.Vertical : MoveOrientation.Horizontal;
// Get new target
ChooseNextPosition();
}
}
I want to show a pixel in the screen.I use openTk in Vs2010.
this is my code in Windows form application:
private void glControl1_Load(object sender, EventArgs e)
{
OpenTK.Graphics.OpenGL.GL.ClearColor(Color.DeepSkyBlue);
OpenTK.Graphics.OpenGL.GL.Color3(Color.Black);
}
private void glControl1_Paint(object sender, PaintEventArgs e)
{
OpenTK.Graphics.OpenGL.GL.Clear(OpenTK.Graphics.OpenGL.ClearBufferMask.ColorBufferBit|OpenTK.Graphics.OpenGL.ClearBufferMask.DepthBufferBit);
OpenTK.Graphics.OpenGL.GL.MatrixMode(MatrixMode.Modelview);
OpenTK.Graphics.OpenGL.GL.LoadIdentity();
OpenTK.Graphics.OpenGL.GL.Begin(BeginMode.Points);
OpenTK.Graphics.OpenGL.GL.Vertex3(3,5,9);
OpenTK.Graphics.OpenGL.GL.End();
glControl1.SwapBuffers();
}
when I run my code I just see a Blue screen.I don't know what is wrong!!!
In order to display anything you will need to set the transformation matrices for projection. In your code you are not setting anything which means that the rendering will not have any idea on where to put your point.
I'd suggest looking into some basic tutorial for working with low-level OpenGL. Most of it should be applicable to your scenario.
Take a look at opentk glcontrol-based apps
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using System.Diagnostics;
namespace GLControlApp
{
public partial class Form1 : Form
{
bool loaded = false;
public Form1()
{
InitializeComponent();
}
Stopwatch sw = new Stopwatch(); // available to all event handlers
private void glControl1_Load(object sender, EventArgs e)
{
loaded = true;
GL.ClearColor(Color.SkyBlue); // Yey! .NET Colors can be used directly!
SetupViewport();
Application.Idle += Application_Idle; // press TAB twice after +=
sw.Start(); // start at application boot
}
void Application_Idle(object sender, EventArgs e)
{
double milliseconds = ComputeTimeSlice();
Accumulate(milliseconds);
Animate(milliseconds);
}
float rotation = 0;
private void Animate(double milliseconds)
{
float deltaRotation = (float)milliseconds / 20.0f;
rotation += deltaRotation;
glControl1.Invalidate();
}
double accumulator = 0;
int idleCounter = 0;
private void Accumulate(double milliseconds)
{
idleCounter++;
accumulator += milliseconds;
if (accumulator > 1000)
{
label1.Text = idleCounter.ToString();
accumulator -= 1000;
idleCounter = 0; // don't forget to reset the counter!
}
}
private double ComputeTimeSlice()
{
sw.Stop();
double timeslice = sw.Elapsed.TotalMilliseconds;
sw.Reset();
sw.Start();
return timeslice;
}
private void SetupViewport()
{
int w = glControl1.Width;
int h = glControl1.Height;
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(0, w, 0, h, -1, 1); // Bottom-left corner pixel has coordinate (0, 0)
GL.Viewport(0, 0, w, h); // Use all of the glControl painting area
}
private void glControl1_Paint(object sender, PaintEventArgs e)
{
if (!loaded)
return;
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.Translate(x, 0, 0);
if (glControl1.Focused)
GL.Color3(Color.Yellow);
else
GL.Color3(Color.Blue);
GL.Rotate(rotation, Vector3.UnitZ); // OpenTK has this nice Vector3 class!
GL.Begin(BeginMode.Triangles);
GL.Vertex2(10, 20);
GL.Vertex2(100, 20);
GL.Vertex2(100, 50);
GL.End();
glControl1.SwapBuffers();
}
int x = 0;
private void glControl1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
x++;
glControl1.Invalidate();
}
}
private void glControl1_Resize(object sender, EventArgs e)
{
SetupViewport();
glControl1.Invalidate();
}
}
}
So I've been putting this graphics transformation program together and suddenly some change I can't figure out has made the app unresponsive. The menus no longer function, and it's supposed to draw axes and a grid on one of the panels... nothing. Any ideas?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Transformer
{
public partial class Transformer : Form
{
/* Initialize parameters */
private bool drawAxes = true;
private bool drawGrid = true;
private List<ObjectSettings> dispObjects = new List<ObjectSettings>();
/* Initialize form */
public Transformer()
{
InitializeComponent();
}
private void Transformer_Load(object sender, EventArgs e)
{
// Populate available objects listbox
string currentDir = Directory.GetCurrentDirectory();
string[] fileEntries = Directory.GetFiles(currentDir + #"\Objects");
foreach (string s in fileEntries) {
int start = s.LastIndexOf(#"\");
int end = s.LastIndexOf(#".");
availObjectsListBox.Items.Add(s.Substring(start + 1, end - start - 1));
} // end foreach
}
/* Paint graphics */
// Paint main form
private void Transformer_Paint(object sender, PaintEventArgs e)
{
}
// Paint graphics panel
private void splitContainer2_Panel1_Paint(object sender, PaintEventArgs e)
{
Rectangle r = splitContainer2.Panel1.ClientRectangle;
Graphics g = splitContainer2.Panel1.CreateGraphics();
Pen axisPen = new Pen(Color.Gray, 2.0f);
Pen gridPen = new Pen(Color.Gray, 1.0f);
g.Clear(Color.White);
if (drawAxes) {
g.DrawLine(axisPen, r.Left + 0.5f * r.Width, r.Top, r.Left + 0.5f * r.Width, r.Bottom);
g.DrawLine(axisPen, r.Left, r.Top + 0.5f * r.Height, r.Right, r.Top + 0.5f * r.Height);
}
if (drawGrid) {
// Vertical lines
int xVal = 0;
int xCenter = r.Width / 2;
g.DrawLine(gridPen, xCenter, r.Top, xCenter, r.Bottom);
for (int i = 0; i < 10; i++) {
xVal += r.Width / 20;
g.DrawLine(gridPen, xCenter + xVal, r.Top, xCenter + xVal, r.Bottom);
g.DrawLine(gridPen, xCenter - xVal, r.Top, xCenter - xVal, r.Bottom);
}
// Horizontal lines
int yVal = 0;
int yCenter = r.Height / 2;
g.DrawLine(gridPen, r.Left, yCenter, r.Right, yCenter);
for (int i = 0; i < 10; i++) {
yVal += r.Height / 20;
g.DrawLine(gridPen, r.Left, yCenter + yVal, r.Right, yCenter + yVal);
g.DrawLine(gridPen, r.Left, yCenter - yVal, r.Right, yCenter - yVal);
}
}
// foreach object in displayed objects
// keep list of displayed objects and their settings (make struct)
g.Dispose();
axisPen.Dispose();
gridPen.Dispose();
}
/* File menu */
private void saveImageToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
/* Options menu */
private void axesOnoffToolStripMenuItem_Click(object sender, EventArgs e)
{
if (drawAxes == true)
drawAxes = false;
else
drawAxes = true;
}
private void gridOnoffToolStripMenuItem_Click(object sender, EventArgs e)
{
if (drawGrid == true)
drawGrid = false;
else
drawGrid = true;
}
/* Help menu */
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox dlg = new AboutBox();
dlg.ShowDialog();
}
/* Other stuff */
private void timer1_Tick(object sender, EventArgs e)
{
Invalidate();
}
// ">>" button
private void availToDispButton_Click(object sender, EventArgs e)
{
dispObjectsListBox.Items.Add(availObjectsListBox.SelectedItem);
}
// "<<" button
private void dispToAvailButton_Click(object sender, EventArgs e)
{
availObjectsListBox.Items.Add(dispObjectsListBox.SelectedItem);
dispObjectsListBox.Items.Remove(dispObjectsListBox.SelectedItem);
}
// Clear all button
private void clearAllButton_Click(object sender, EventArgs e)
{
}
// Update preview box
private void availObjectsListBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Thanks!
Try commenting out (separately) the "load" and "paint" code, see which is the problem.
If the problem is the paint... I wonder - rather than creating your own Graphics, use the one given to you? Namely, e.Graphics. Note that you didn't create this, so it isn't your job to Dispose() it (so don't do that). I would also cache the Pen etc in fields rather than create them each time. Note that if you do create a Pen (etc) in a method, then using is a better way to Dispose() it.
There is also a foreach comment in the paint code that suggests something has been removed - this may be relevant to the problem...
If this is happening when loading then obviously the amount of files in the directory could be causing the GUI thread to hang.
Other then that my quick look through only makes me think to check the bools you are using to control drawing and to make sure that the panel you are using the paint event for is actually visible.
You should also check that your timer is actually ticking, and check its interval.
I would also look at using the using statement, or at least a finally block for your dispose. But that isn't what your question is about.
Most of those are obvious and you might have already checked them all before posting here, but I thought I would put up something in case you had missed it. Hopefully I will get a chance to look through in more detail and spot something else.