我只需要在鼠标点击图像时移动图像。
我有这个动作:
if (Mouse.GetState().LeftButton == ButtonState.Pressed &&
previousMouseState.LeftButton != ButtonState.Pressed)
{
xpos = rnd.Next(windowWidth - texture.Width);
ypos = rnd.Next(windowHeight - texture.Height);
}
previousMouseState = Mouse.GetState();
但我需要某种复合if
逻辑才能使它只有在点击纹理时才会移动。
答案 0 :(得分:3)
我认为您的texture
对象不仅仅是Texture2D
。
绘制精灵时,你既有位置又有大小。这样的事情应该有效:
var currentMouseState = Mouse.GetState();
if (currentMouseState.LeftButton == ButtonState.Pressed &&
previousMouseState.LeftButton != ButtonState.Pressed)
{
Vector2 mousePosition = new Vector2(currentMouseState.X,currentMouseState.Y);
mousePosition-=sprite.Position;
/// .Bounds is a property of Texture2D, and returns a Rectangle() struct
var spriteWasClicked = sprite.Bounds.Contains(mousePosition.X,mousePosition.Y);
if(spriteWasClicked)
{
xpos = rnd.Next(windowWidth - texture.Width);
ypos = rnd.Next(windowHeight - texture.Height);
// update sprite position with to xpos,ypos here.
}
}
previousMouseState = currentMouseState;
答案 1 :(得分:0)
我认为Reactive Extensions对此非常适合。
您上面的代码可能是基于触发事件的计时器/调度程序调用的。您可以通过调用IObservable<T>
将其更改为Observable.FromEvent
method实施。
完成后,您可以使用IObservable<T>
上的LINQ operators来获取鼠标按下之间的“窗口”。您很可能会像TakeUntil
method这样使用:
// Your initial observable.
var timerObservable = Observable.FromEvent(timer, "TimerFired");
// The button pressed.
var pressed = timerObservable.
Where(t => Mouse.GetState().LeftButton == ButtonState.Pressed);
// The button not pressed.
var notPressed = timer.Observable.
Where(t => Mouse.GetState().LeftButton != ButtonState.Pressed);
// Observe the not pressed until it is pressed.
// Make sure to repeat.
var pressed = notPressed.SkipUntil(pressed).Repeat();
然后你可以调用Subscribe
method并传递一个代表,代码将在按下按钮时被调用。
您甚至可以通过拨打Observable.Timer
method来更换计时器,以生成您正在等待的计时器。