我有一个Picturebox可以用(W,A,S,D)键移动,但是它非常不稳定,您一次只能按下一个键。还有其他方法可以使“精灵”更平滑地移动吗?
这是我尝试过的代码:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
int offset = 10;
if (e.KeyChar == 'a')
{
pictureBox1.Location = new Point(pictureBox1.Location.X - offset, pictureBox1.Location.Y);
}
else if (e.KeyChar == 'w')
{
pictureBox1.Location = new Point(pictureBox1.Location.X, pictureBox1.Location.Y - offset);
}
else if (e.KeyChar == 's')
{
pictureBox1.Location = new Point(pictureBox1.Location.X, pictureBox1.Location.Y + offset);
}
else if (e.KeyChar == 'd')
{
pictureBox1.Location = new Point(pictureBox1.Location.X + offset, pictureBox1.Location.Y);
}
}
答案 0 :(得分:0)
您最好在内部更新位置,而不是通过调用type TextFieldData = { value: string }
type TextField = { type: 'text', data: TextFieldData }
type SelectFieldData = { options: string[], selectedValue: string }
type SelectField = { type: 'select', data: SelectFieldData }
type FormField = TextField | SelectField
function renderTextField(props: TextFieldData) {}
function renderSelectField(props: SelectFieldData) {}
const fieldMapping = {
text: renderTextField,
select: renderSelectField,
}
// This won't work!
function renderFieldDoesNotWork(field: FormField) {
const renderFn = fieldMapping[field.type]
// Type 'TextFieldData' is missing the following properties from type 'SelectFieldData': options, selectedValue
renderFn(field.data)
}
// This works
function renderFieldWorks(field: FormField) {
if (field.type === 'text') {
const renderFn = fieldMapping[field.type]
renderFn(field.data)
} else if (field.type === 'select') {
const renderFn = fieldMapping[field.type]
renderFn(field.data)
}
}
答案 1 :(得分:0)
要延伸到Babak并回答您的另一部分(一次只按一个键),请将您的else if更改为一系列if语句。如果使用else,则一旦其中一个为真,它就会中断序列,这意味着一旦按下一个键,就不会寻找其他键。