Hi, I am really new to Unity3d. I’m creating a gallery shooting game and I have a gun object that only moves along the x axis. I want to limit the movement just to the edge of the screen. Once it hits the edge of the screen, I have it hard coded to move back into the screen a few pixels. But it looks rough since it flickers when it hits the edge of the screen. I’ve tried setting the transforms.position.x to equal the transform.position.x once it hits the edge of the screen but the gun object will continue to move off screen. Currently this is the code:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public float maxStrafeSpeed = 0.01f; // max move speed, recommend a very low float, will move too fast if too high
public float maxMouseSpeed = 3.0f; // max speed the gun will rotate to where the mouse is pointing
private float h; // horizontal axis
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
PlayerMovementStrafing ();
PlayerMovementMouseAim ();
}
void PlayerMovementStrafing()
{
// get input
h = Input.GetAxis ("Horizontal") * maxStrafeSpeed;
Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
if (pos.x < 0.0f)
{
transform.position = new Vector3(-0.6f, transform.position.y, transform.position.z);
Debug.Log("Left edge of view");
}
else if (pos.x > 1.0f)
{
transform.position = new Vector3(0.6f, transform.position.y, transform.position.z);
Debug.Log("Right edge of view");
}
this.transform.Translate (new Vector3 (h, 0.0f, 0.0f));
}
void PlayerMovementMouseAim ()
{
transform.Rotate(Vector3(Input.GetAxis("Mouse Y"), Input.GetAxis("Mouse X"), 0) * (Time.deltaTime * maxMouseSpeed));
}
}