More Fluent Image Movement

226 views Asked by At

So I'm messing around, getting a hang of things and I'm making a picture box move, which I have done. However could someone show me how to make the movement more fluent but not slow it down so much?

Code:

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;

namespace meh
{
    public partial class Form1 : Form
    {
        PictureBox Test = new PictureBox();
        public Form1()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.None;
            WindowState = FormWindowState.Maximized;


           Test.Image = Properties.Resources.PlatinumGrass;
            Test.Location = new Point(0, 0);
            Test.Width = 32;
            Test.Height = 32;
            this.Controls.Add(Test);
            KeyDown += new KeyEventHandler(Form1_KeyDown);


        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            int x = Test.Location.X;
            int y = Test.Location.Y;
            int xmax = Screen.PrimaryScreen.Bounds.Width - 32;
            int ymax = Screen.PrimaryScreen.Bounds.Height - 32;
            if (e.KeyCode == Keys.Right && x < xmax ) x += 20;
            if (e.KeyCode == Keys.Left && x > 0) x -= 20;
            if (e.KeyCode == Keys.Up && y > 0) y -= 20;
            if (e.KeyCode == Keys.Down && y < ymax) y += 20;

            Test.Location = new Point(x, y);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
1

There are 1 answers

1
Hamid Pourjam On BEST ANSWER

I suggest not using winforms for game development

but you can add these lines to form constructor to make some improvements.

SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);   

also you can add a for loop for movement part to improve it a little bit

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    int xmax = Screen.PrimaryScreen.Bounds.Width - 32;
    int ymax = Screen.PrimaryScreen.Bounds.Height - 32;

    for (int i = 0; i < 10; i++)
    {
        int x = Test.Location.X;
        int y = Test.Location.Y;
        if (e.KeyCode == Keys.Right && x < xmax) x += 2;
        if (e.KeyCode == Keys.Left && x > 0) x -= 2;
        if (e.KeyCode == Keys.Up && y > 0) y -= 2;
        if (e.KeyCode == Keys.Down && y < ymax) y += 2;
        Test.Location = new Point(x, y);
        Application.DoEvents();
    }
}