Ok I’ve got it to work now.
this is the final, working code:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody player;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
void SetTransformX(float n)
{
player.transform.position = new Vector3(n, player.transform.position.y, player.transform.position.z);
}
void SetTransformY(float n)
{
player.transform.position = new Vector3(player.transform.position.x, n, player.transform.position.z);
}
// Update is called once per frame
void FixedUpdate () {
player.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d"))
{
player.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
player.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("w"))
{
player.AddForce(0, sidewaysForce * Time.deltaTime, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("s"))
{
player.AddForce(0, -sidewaysForce * Time.deltaTime, 0, ForceMode.VelocityChange);
}
if (player.transform.position.x >= 10) { SetTransformX(10.0f); player.velocity = new Vector3(0, player.velocity.y, player.velocity.z); }
if (player.transform.position.x <= -10) { SetTransformX(-10.0f); player.velocity = new Vector3(0, player.velocity.z, player.velocity.z); }
if (player.transform.position.y <= 0) { SetTransformY(0.0f); player.velocity = new Vector3(player.velocity.x, 0, player.velocity.z); }
if (player.transform.position.y >= 10) { SetTransformY(10.0f); player.velocity = new Vector3(player.velocity.x, 0, player.velocity.z); }
}
}
— old response —
Ok, I might need to clarify my struggle a bit.
I understand the code you guys posted and that is also what I had in mind, but I don’t know how to do it with the code I currently have.
This is my current player movement code:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody player;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
// Update is called once per frame
void FixedUpdate () {
player.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d"))
{
player.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
player.transform.Rotate(0, 0, 20 * Time.deltaTime);
}
if (Input.GetKey("a"))
{
player.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
player.transform.Rotate(0, 0, -20 * Time.deltaTime);
}
if (Input.GetKey("w"))
{
player.AddForce(0, sidewaysForce * Time.deltaTime, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("s"))
{
player.AddForce(0, -sidewaysForce * Time.deltaTime, 0, ForceMode.VelocityChange);
}
}
}
If I use this simple code-snippet:
if (player.transform.position.x >= 10) { player.transform.position.x = 10; }
Visual Studio gives me the following error:
player.transform.position.x is not a variable and therefore cannot be changed
so this seems not to work… :-/