Hello! I’m doing a project from this book called “Unity Game Development in 24 Hours” by Ben Tristem and Mike Geig. In Chapter 15 we use Mathf.Clamp to help keep the ship on screen. Here is the code -
using UnityEngine;
using System.Collections;
public class ShipControlScript : MonoBehaviour {
public float playerSpeed = 10f;
public GameControl gameController;
public GameObject bulletPrefab;
public float reloadTime = 0.5f; //Bullets can fire every 0.5 seconds
private bool invert = false;
private float elapsedTime = 0;
// Update is called once per frame
void Update() {
elapsedTime += Time.deltaTime;
//Move player from left to right
float xMovement = Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;
float xPosition = Mathf.Clamp(xMovement, -7f, 7f); //Keeps ship on screen
if (invert){
transform.Translate(xPosition * -1, 0f, 0f);
}
else{
transform.Translate(xPosition, 0f, 0f);
}
if (Input.GetButtonDown("Shoot") && elapsedTime > reloadTime) {
Vector3 spawnPos = transform.position;
spawnPos += new Vector3(0, 1f, 0);
Instantiate(bulletPrefab, spawnPos, Quaternion.identity);
invert = !invert;
elapsedTime = 0f;
}
if (reloadTime > 0.2f){
reloadTime -= Time.deltaTime / 300;
}
}
void OnTriggerEnter2D (Collider2D other){
gameController.PlayerDied();
}
}
Thing is that ship doesn’t stay within -7f and 7f. It continues on and on. I even copy pasted the code that they provided and the ship still isn’t restricted. Any idea why? Thanks for any help in advance.
