3
\$\begingroup\$

So I want to make an on rails shooter like that of Star-Fox in the Unity engine. What I would like to do is limit the ship from moving off the screen. You move along the X and Y axis so i wont have to keep these invisible colliders in their place but I cant get another way to work.

and I know I have to find a way to convert camera space to world space I just can't find a way how.

This is my current controller and I commented a few failed attempts.

also I'm using a perspective camera and I'd like to keep the rigibody movement if possible.

public float turnSpeed = 10;//Horizontal

//private Vector3 moveDirection = Vector3.zero;

public Rigidbody rb;
void Start()
{
    rb = GetComponent<Rigidbody>();
}
void Update()
{//Screen.width
    //transform.position = new Vector3(Mathf.Clamp(transform.position.x, -holdMyRatio, holdMyRatio),
   //                                  Mathf.Clamp(transform.position.y, -holdMyRatio, holdMyRatio), 0);
    //CharacterController controller = GetComponent<CharacterController>();
    rb.AddRelativeForce(Vector3.right * turnSpeed * Input.GetAxis("Horizontal"));
    rb.AddRelativeForce(Vector3.up * turnSpeed * Input.GetAxis("Vertical"));
  //  moveDirection.x = Input.GetAxis("Mouse X") * turnSpeed;// * Time.smoothDeltaTime;
   // moveDirection.y = Input.GetAxis("Mouse Y") * turnSpeed;// * Time.smoothDeltaTime;
  //  controller.Move(moveDirection * Time.smoothDeltaTime);
}
\$\endgroup\$
1
\$\begingroup\$

http://answers.unity3d.com/questions/799656/how-to-keep-an-object-within-the-camera-view.html

Vector3 pos = Camera.main.WorldToViewportPoint (ship.transform.position);
pos.x = Mathf.Clamp01(pos.x);
pos.y = Mathf.Clamp01(pos.y);
ship.transform.position = Camera.main.ViewportToWorldPoint(pos);

As the answerer noted in that question, Viewport space has the origin (0,0) in the lower-left-hand corner, with the upper-right-hand being (1,1).

This will clamp the movement; i.e. it will feel like an invisible wall around the edges of the screen.

Just make sure this code happens after any physics movement adjustments, and you should be able to keep your rigidbody stuff. If you encounter jitter, consider changing the code to something like this:

Vector3 pos = Camera.main.WorldToViewportPoint (ship.transform.position);
pos.x = Mathf.Clamp01(pos.x);
pos.y = Mathf.Clamp01(pos.y);

Vector3 speed = ship.rb.velocity;
if(pos.x == 0 || pos.x == 1)
    speed.x = 0;
if(pos.y == 0 || pos.y == 1)
    speed.y = 0;

ship.transform.position = Camera.main.ViewportToWorldPoint(pos);
ship.rb.velocity = speed;
\$\endgroup\$
  • \$\begingroup\$ It works perfectly and there doesn't seem to be any jittering so it works just fine thanks \$\endgroup\$ – Ryan Henry Oct 3 '15 at 2:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.