My goal is to move a picturebox back and forth. My issue is how to do this.
I have written the following:
int x = enemy.Location.X;
int y = enemy.Location.Y;
enemy.Location = new Point(x+-1, y);
This moves the picturebox off-screen, left. After moving left, I'd like it to move right, so that it moves back and forth - in a continuous loop.
The noob that I am, I tried:
if (x < 40)
enemy.Location = new Point(x - -100, y);
else if (x > 400)
enemy.Location = new Point(x - 5, y);
This proves unsuccessful - the box doesn't seem to move on reaching pixel 40.
Is there a simple solution that you can prod me towards, or have I dug an early grave for myself?!
I should specify: I am writing in C# per college assignment requirements.
Cheers.
When moving left, when the x location reaches 0, change direction and move right.
When moving right, you need to use the width of the screen minus the width of your picturebox.
System.Windows.SystemParameters.PrimaryScreenWidth
edit:
Or better yet, use the width of your form minus the width of the picturebox. Then it will still work if its not maximized.
Setup a variable that toggles between negative and positive values to make it go left and right. You toggle the direction by multiplying by -1. Then you simply add that variable to the current X value like this:
private int direction = -1; // this can be values other than 1 to make it jump farther each move
private void timer1_Tick(object sender, EventArgs e)
{
int x = enemy.Location.X + direction;
if (x <= 0)
{
direction = -1 * direction;
x = 0;
}
else if (x >= this.ClientRectangle.Width - enemy.Width)
{
direction = -1 * direction;
x = this.ClientRectangle.Width - enemy.Width;
}
enemy.Location = new Point(x, enemy.Location.Y);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.