Reputation: 43
I know this has been asked but can't figure out how to solve this.
if (this.gameObject.tag == "1Team"){
unitGO.transform.position += transform.right * movementSpeed * Time.deltaTime;
} else if (this.gameObject.tag == "2Team"){
unitGO.transform.position += transform.left * movementSpeed * Time.deltaTime;
}
Unity marks in red transform.left ( Transform' does not contain a definition for 'left' ), so I dont know how to move my character to the left. I have tried using -Transform.right
, Transform.right * -movementSpeed
, new Vector3( - 1,0,0)
, unitGO.transform.position -= new Vector3(1,0,0) * movementSpeed * Time.deltaTime;
and other options without getting the movement I want.
if I change the tag from the GameObject I want to move, it actually moves right, so I dont think it's anything related to attaching scripts
https://docs.unity3d.com/ScriptReference/Vector3-left.html
Any suggestions?
Thank you
Upvotes: 0
Views: 3513
Reputation: 90679
While Vector3.left
exists, for Transform
there is only transform.right
.
Which is no problem since for moving left you simply use -transform.right
.
Now note that your intempts of using new Vector3
also didn't work since if you use that you move in global space along Unity's X axis .. not in local space.
Now there are multiple possible solutions:
For moving in your local space do e.g.
if (gameObject.CompareTag("1Team"))
{
unitGO.transform.position += transform.right * movementSpeed * Time.deltaTime;
}
else if (gameObject.CompareTag("2Team"))
{
unitGO.transform.position -= transform.right * movementSpeed * Time.deltaTime;
// Same as
//unitGO.transform.position += -transform.right * movementSpeed * Time.deltaTime;
}
Or if you wan to move in Unity's global X axis then
if (gameObject.CompareTag("1Team"))
{
unitGO.transform.position += Vector3.right * movementSpeed * Time.deltaTime;
}
else if (gameObject.CompareTag("2Team"))
{
unitGO.transform.position += Vector3.left * movementSpeed * Time.deltaTime;
// Same as
//unitGO.transform.position -= Vector3.right * movementSpeed * Time.deltaTime;
}
Or if you actually rather wanted to move along the local X axis of the object you are moving you could rather use Translate
which by default uses the local space of the moved object
if (gameObject.CompareTag("1Team"))
{
unitGO.transform.Translate(Vector3.right * movementSpeed * Time.deltaTime);
}
else if (gameObject.CompareTag("2Team"))
{
unitGO.transform.Translate(Vector3.left * movementSpeed * Time.deltaTime);
// Same as
//unitGO.transform.Translate(-Vector3.right * movementSpeed * Time.deltaTime);
}
In general rather use CompareTag
instead of ==
to throw an error if there is a typo
Upvotes: 2