我遇到了一个我似乎无法解决的问题,如果 KeyPressed == false 的测试确实播放了“car_still.wav”,但是如果 KeyPressed == true 的测试在全部。
我该如何解决上述问题以及,
如何将 player/player2.Stop() 集成到任一 if 语句中(如果一个声音播放,另一个停止),因为现在我收到错误“当前不存在名称‘player’语境”。
先感谢您。
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
private int carX;
private int roadTilesY = -193;
int speedY;
int time;
bool keyPressed;
System.Media.SoundPlayer player;
System.Media.SoundPlayer player2;
public Form1()
{
InitializeComponent();
gameSounds();
carX = this.Width / 2 - 30;
speedY = 0;
time = 0;
}
private void gameSounds()
{
if (!keyPressed)
{
player = new System.Media.SoundPlayer(@"C:\Users\Parker\Desktop\Game\car_still.wav");
player.PlayLooping();
}
else
{
player2 = new System.Media.SoundPlayer(@"C:\Users\Parker\Desktop\Game\car_speeding.wav");
player2.PlayLooping();
if (player != null)
player.Stop();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
PlayerCar.Invalidate();
PlayerCar.Location = new Point(carX, PlayerCar.Location.Y);
RoadTileAnimation();
npcCarMovement();
if (keyPressed == true)
{
label1.Text = "Key pressed";
}
if (keyPressed == false)
{
label1.Text = "key not pressed";
}
label2.Text = "" + speedY;
}
private void RoadTileAnimation()
{
roadTilesY = roadTilesY - speedY;
if (roadTilesY >= -50)
{
roadTilesY = -193;
}
roadTiles.Location = new Point(roadTiles.Location.X, roadTilesY);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
carX = carX - 15;
if ((carX + PlayerCar.Width) > this.Width)
{
carX = this.Width - PlayerCar.Width - 10;
}
}
if (e.KeyCode == Keys.Right)
{
carX = carX + 15;
if ((carX + PlayerCar.Width) > this.Width)
{
carX = this.Width - PlayerCar.Width - 10;
}
}
if (e.KeyCode == Keys.Up)
{
speedY = speedY - 1;
keyPressed = true;
}
if (e.KeyCode == Keys.Down)
{
speedY = speedY + 3;
if (speedY > 0)
{
speedY = 0;
}
keyPressed = true;
}
}
private void timer2_Tick(object sender, EventArgs e)
{
if (speedY != 0)
{
time++;
time = time - speedY / 8;
timeLabel.Text = time.ToString() + " m";
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
keyPressed = false;
}
if (e.KeyCode == Keys.Down)
{
keyPressed = false;
}
if (e.KeyCode == Keys.Left)
{
keyPressed = false;
}
if (e.KeyCode == Keys.Right)
{
keyPressed = false;
}
}
private void npcCarMovement()
{
npcCar.Invalidate();
npcCar.Location = new Point(npcCar.Location.X, npcCar.Location.Y + 2);
npcCar.Location = new Point(npcCar.Location.X, npcCar.Location.Y - speedY);
}
}
}