Setting Specific Borders in X and Y axis in Top-Do

2019-08-22 14:15发布

got another quick question for you.

I am making a 2D top-down platformer game where the player can only move on the x and y axis.

I am trying to set the borders of the map so that the player and all other objects can't cross it but with the code im trying it gives me the error:

"Cannot modify a value type return value of 'UnityEngine.Transform.position'. Consider storing the value in a temporary variable."

Here is the code I am trying, it looks pretty simple but given my experience level with C# I am unable to tell why it isn't allowed:

using UnityEngine; using System.Collections;

public class BorderScript : MonoBehaviour {

public Vector2 Position;

// Use this for initialization
void Start () {


}

// Update is called once per frame
void Update () {

    if (this.transform.position.x >= 50) {
        this.transform.position.x = 50;
            }

    if (this.transform.position.x <= -50) {
        this.transform.position.x = -50;
    }

    if (this.transform.position.y <= 50) {
        this.transform.position.y = 50;
    }

    if (this.transform.position.y <= -50) {
        this.transform.position.y = -50;
    }
}
}

Thanks in advance guys, your help will be much appreciated..

标签: c# unity3d
1条回答
三岁会撩人
2楼-- · 2019-08-22 14:42

You cannot modify a value for a single axis at a time, in C#. You have to reassign the entire vector:

this.transform.position = new Vector3(transform.position.x, 50, transform.position.z);

,when you modify, as an example, the Y axis to be equal to 50 units (your instruction this.transform.position.y = 50; must be replaced with the instruction of mine, and the other accordingly).

查看更多
登录 后发表回答