Hi, I’m new to Unity and programming, I’ve managed to write a PlayerController script (watching some tutorials) but I think it’s wrong. I have collisions only with a rigidbody but when i add it to the player it goes up, if I freeze the Y coordinate then it works but collisions works in a strange way, sometimes while hitting other objects boxes the player get “launched” in a direction and can’t move anymore. Can anyone help me fix this script?
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
public CharacterController controller;
public GameObject bulletPrefab;
public Transform bulletSpawn;
public int stardustcount;
public Slider stardustbar;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
transform.position += transform.forward * Time.deltaTime * moveSpeed;
if (Input.GetButtonDown("Fire1"))
{
Fire();
}
if (Input.GetButton("Fire3"))
{
moveSpeed = 10;
}
else
{
moveSpeed = 30;
}
}
void Fire()
{
var bullet = (GameObject)Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 60;
Destroy(bullet, 5.0f);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Stardust"))
{
Destroy(other.gameObject);
stardustcount = stardustcount + 1;
stardustbar.value = stardustcount;
}
}
}
The player’s direction is managed in the CameraController script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
public float rotateSpeed;
public Transform pivot;
public Vector3 offset;
public bool useOffsetValues;
public bool invertY;
void Start()
{
if (!useOffsetValues)
{
offset = target.position - transform.position;
}
pivot.transform.position = target.transform.position;
pivot.transform.parent = target.transform;
Cursor.lockState = CursorLockMode.Locked;
}
void LateUpdate()
{
//Gets the X position of the mouse & rotate the target
float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
target.Rotate(0, horizontal, 0);
//Moves the camera based on the current rotation of the target & the original offset
float desiredYAngle = target.eulerAngles.y;
float desiredXAngle = pivot.eulerAngles.x;
Quaternion rotation = Quaternion.Euler(desiredXAngle, desiredYAngle, 0);
transform.position = target.position - (rotation * offset);
if(transform.position.y < target.position.y)
{
transform.position = new Vector3(transform.position.x, target.position.y - .5f, transform.position.z);
}
transform.LookAt(target);
}
}