coder008 coder008 - 2 months ago 11
C# Question

Space Shooter player colision not working properly

im trying to do the tutorial in unity on the official unity website page, and i have some doubts, because the tutorial is kinda old and the things doesnt work right how he do it, so i already set the player and the background, and now i must write the script to put the player on move and check the colisions between the x and z axis, so what i did was basicly using the Math.clamp method, but when i set the x axis for example, to a min -6 and max 6, it just moves between -1 and 1 same happens for the z axis, and i dont know why it happen :S

here is the code

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

private Rigidbody rb;
public float velocity;
public float xMin, xMax, zMin, zMax;

void Start () {
rb = GetComponent<Rigidbody> ();
velocity = 3.0f;
xMin = -6.0f;
xMax = 6.0f;
zMin = -4.0f;
zMax = 7.0f;
}

// Update is called once per frame
void FixedUpdate () {
float xAxis = Input.GetAxis ("Horizontal");
float zAxis = Input.GetAxis ("Vertical");
rb.velocity = new Vector3 (xAxis, 0.0f, zAxis) * velocity;
rb.position = new Vector3 (Mathf.Clamp (xAxis, xMin, xMax), 0.0f, Mathf.Clamp (zAxis, zMin, zMax));
}

}

Answer

Mathf.Clamp sets the bounds for you values. So it can't go more or less than these. if you want the values to go further than -6 and +6, Just increase xMin, xMax, zMin, zMax values from inspector. And Input.GetAxis has range between -1 to +1 so you wont get further than that. So try multiplying the xAxis and zAxis values by some large number. 10 for example.

void FixedUpdate () 
{
    float xAxis = Input.GetAxis ("Horizontal") * 10;
    float zAxis = Input.GetAxis ("Vertical") * 10;
    rb.velocity = new Vector3 (xAxis, 0.0f, zAxis) * velocity;
    rb.position = new Vector3 (Mathf.Clamp (xAxis, xMin, xMax), 0.0f, Mathf.Clamp (zAxis, zMin, zMax));
}
Comments