开发者

Moving an image when clicked on by the mouse in a C# XNA game

I need to have an image move only when it is clicked on by the mouse.

I have this for the movement:

if (Mouse.GetState().LeftButton == ButtonState.Pressed &&
    previousMouseState.LeftButton != ButtonState.Pressed)
{
    xpos = rnd.Next(windowWidth - texture.Width);
    ypos = rnd.Next(win开发者_Go百科dowHeight - texture.Height);
}

previousMouseState = Mouse.GetState();

But I need some sort of compound if logic to make it so it only moves if the texture is clicked on.


I assume that your texture object isn't just a Texture2D.

When drawing a sprite, you have both position and size. Something like this should work:

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;


I think that the Reactive Extensions are perfect for this.

The code you have above is probably called based on a timer/scheduler which fires an event. You can change that into an IObservable<T> implementation through a call to the Observable.FromEvent method.

Once you have that, you can then use the LINQ operators on the IObservable<T> to get the "windows" between mouse presses. You would more than likely use the the TakeUntil method like so:

// 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();

You can then call the Subscribe method and pass a delegate with your code which will be called while the button is pressed.

You can even replace the timer with a call to the Observable.Timer method to generate your timer which you are waiting on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜