I wrote such a property (representing direction for my XNA game object):

public Vector2 Direction
{
    get { return direction; }
    protected set
    {
        (direction = value).Normalize(); // ***
        angle = MathHelper.WrapAngle((float)Math.Atan(direction.X / direction.Y));
    }
}

set sets two equivalent fields which represent object's orientation in angle and simultaneously in normalized vector.

Starting game failed because line marked by *** failed. It doesn't normalize vector.
I changed this line to:

direction = value;
direction.Normalize();

and it works fine... Why?
I assumed that in line marked by *** first operation is assigning value and then normalising direction. But it's not true.

___ ___ ____
Normalize() is method from Vector2 class.

//
// Summary:
//     Turns the current vector into a unit vector. The result is a vector one unit
//     in length pointing in the same direction as the original vector.
public void Normalize();
有帮助吗?

解决方案

I am assuming Vector2 is a struct, or value type, which means it is passed-by-value and not by reference. When you assign value to direction, you are setting direction to a copy of value. Additionally, the object returned by the expression (direction = value) is a copy, and not the same instance that is in direction. You are calling Normalize on an object that is never stored outside of the setter block.

For this same reason you cannot call methods or set properties on a struct returned from a property getter on a class. For instance, if the property from your example is in a class named Monkey, note:

Monkey m = new Monkey();
m.Direction = new Vector2(...);
m.Direction.X = 2; // This will not compile.
m.Direction.Normalize(); // This will not do what you expect.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top