Adariel Lzinski
Adariel Lzinski

Reputation: 1121

How to multiply Vectors with Double?

I'm trying to make a sprite move back and forth with this equation here:

SpriteTexture sprite;
Vector2 position;
Vector2 p1 = new Vector2(0, 100), 
        p2 = new Vector2(0, 0);
double currentTime = 0, timestep = 0.01;
...    
protected override void Update(GameTime gameTime)
{
 position = currentTime * p1 + (1 - currentTime) * p2;
 currentTime += timestep;
 if (currentTime >= 1 || currentTime <= 0)
 {
   timestep *= -1;
 }
}

I keep getting the error: "Operator '*' cannot be applied to operands of type 'double' and Microsoft.Xna.Framework.Vector2"

Upvotes: 0

Views: 7581

Answers (4)

bhaskarc
bhaskarc

Reputation: 9531

Try to use:

Vector2.Multiply Method (Vector2, Single)

API as documented here:

http://msdn.microsoft.com/en-us/library/bb198129.aspx

You cannot multiply a vector with a double using * operator and this is what the error is complaining.

Upvotes: 1

Cyral
Cyral

Reputation: 14153

Try using Vector2.Multiply or converting your double to a float, and multiplying the Vector2 by the currentTime

1.

position = Vector2.Multiply(p1, (float)currentTime) +
    Vector2.Multiply(p2, (float)(1 - currentTime));

2.

position = (p1 * (float)currentTime) + (p2 * (float)(1 - currentTime));

Upvotes: 2

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48580

This line is causing problem

position = currentTime * p1 + (1 - currentTime) * p2

Here you are trying to multiply currentTime a double with p1 a Vector Instance.

To multiply a Vector instance you need to use Vector.Multiply

Upvotes: 0

Victor Chelaru
Victor Chelaru

Reputation: 4847

Vector2 supports multiplication by floats, or you can manually multiply the individual components of a vector by the double (which you'd cast to a float).

For example:

 position = currentTime * (float)p1 + ((float)(1 - currentTime)) * p2;

Or if you wanted to do individual multiplication of a vector

 // Assuming myVector is a Vector3:
 myVector.X *= (float)someDoubleValue;
 myVector.Y *= (float)someDoubleValue;
 myVector.Z *= (float)someDoubleValue;

Upvotes: 1

Related Questions