Space shooter tutorial code

Following the code, it does not work because of updates. Trying to insert the fixes as a beginner is very confusing. I would very much like to see how the mathf.clamp with the xMin and xMax, zMin and zMax works in Unity 5. 6 1.

if someone could post a clean code that works now, that would be the most helpful.

Thank you in advance

I am in the same boat as you, but was able to find some solutions online thanks to answers.unity3d.com and it’s community. So hopefully this will be returning the favor to some degree. See my code below:

using UnityEngine;
using System.Collections;

[System.Serializable]
public class Boundary 
{
	public float xMin, xMax, zMin, zMax;
}

public class PlayerController : MonoBehaviour 
{

	private Rigidbody rb;
	public float speed;
	public float tilt;
	public Boundary boundary;

	public GameObject shot;
	public Transform shotSpawn;
	public float fireRate;

	private float nextFire;

	void Start() {
		rb = GetComponent<Rigidbody> ();
	}

	void Update ()
	{
		if (Input.GetButton ("Fire1") && Time.time > nextFire) //This code pulled from Input.GetButton in documentation
		{
			nextFire = Time.time + fireRate;
			//GameObject clone = 
			Instantiate (shot, shotSpawn.position, shotSpawn.rotation); //as GameObject;

			gameObject.GetComponent<AudioSource>().Play ();
		}
	}

	void FixedUpdate() 
	{
		float moveHorizontal = Input.GetAxis ("Horizontal");
		float moveVertical = Input.GetAxis ("Vertical");

		Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
		rb.AddForce (movement * speed);

		rb.position = new Vector3 (

			Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax), 
			0.0f,
			Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)
		); 
		rb.rotation = Quaternion.Euler (0.0f, 0.0f, rb.velocity.x * -tilt);

	}

} 

Two elements that gave me the most repeated trouble in the code was the short calls. For instance, they like to say rb instead of rigidbody in that tutorial. So I would have to create rb = GetComponent<Rigidbody> (); in the void Start() { each time something like that was used. If you’re by chance using the .rb.position reference for your X vector in the mathf.clampyou’ll need that void Start reference to make it work correctly.

If this doesn’t resolve your issues, leave some more details and I’ll be happy to try and help find them with ya.

  • Matches