Simply put, I’m trying to do a Top-Down space shooter, using rigidbody physics so as to simulate collisions, etc. For whatever reason, as the rigidbody gains speed, it slowly starts moving off screen. Collision also seems to break. Here’s the code:
using UnityEngine;
using System.Collections;
public class InputHandler : MonoBehaviour
{
Transform Pcamera;
Quaternion PlayerRotation;
Transform PlayerMesh;
Transform myTransform;
float velX;
float velZ;
float maxVel = 25;
public float speed = 2.0f;
public Rigidbody rbody;
void Awake() {
myTransform = transform;
}
void Start () {
Pcamera = GameObject.Find("Main Camera").transform;
PlayerMesh = GameObject.Find("PlayerMesh").transform;
PlayerRotation = PlayerMesh.rotation;
Velocity = PlayerMesh.rigidbody.velocity;
velX = PlayerMesh.rigidbody.velocity.x;
velZ = PlayerMesh.rigidbody.velocity.z;
}
void FixedUpdate () {
HandleInput();
PMeshRotate();
velX = PlayerMesh.rigidbody.velocity.x;
velZ = PlayerMesh.rigidbody.velocity.z;
Velocity = PlayerMesh.rigidbody.velocity;
VelocityChecker();
}
void Update() {
myTransform.position = PlayerMesh.position;
Vector3 CameraPosition = myTransform.position;
CameraPosition.y = Pcamera.position.y;
Pcamera.position = CameraPosition;
}
void VelocityChecker() {
if(PlayerMesh.forward.x * PlayerMesh.rigidbody.velocity.x>maxVel)
velX = maxVel;
if(PlayerMesh.forward.x * PlayerMesh.rigidbody.velocity.x<-maxVel)
velX=-maxVel;
if(PlayerMesh.forward.z * PlayerMesh.rigidbody.velocity.z>maxVel)
velZ = maxVel;
if(PlayerMesh.forward.z * PlayerMesh.rigidbody.velocity.z<-maxVel)
velZ=-maxVel;
PlayerMesh.rigidbody.velocity = new Vector3(velX, 0, velZ);
}
void HandleInput() {
if(Input.GetKey(KeyCode.W)) {
PlayerMesh.rigidbody.AddRelativeForce(0, 0, 5);
}
if(Input.GetKey(KeyCode.S)) {
PlayerMesh.rigidbody.AddRelativeForce(0, 0, -5);
}
if(Input.GetKey(KeyCode.D)) {
PlayerMesh.rigidbody.AddRelativeForce(5, 0, 0);
}
if(Input.GetKey(KeyCode.A)) {
PlayerMesh.rigidbody.AddRelativeForce(-5, 0, 0);
}
}
void PMeshRotate() {
Vector3 mousePos = Input.mousePosition;
mousePos.z = -10;
Quaternion temprotation = Quaternion.LookRotation(PlayerMesh.position - Pcamera.camera.ScreenToWorldPoint(mousePos), Vector3.up);
PlayerRotation = Quaternion.Slerp(PlayerRotation, temprotation, Time.deltaTime * 5.0f);
PlayerRotation.z = 0;
PlayerRotation.x = 0;
PlayerMesh.rigidbody.MoveRotation(PlayerRotation);
}
}
Here’s also a 1 to my project, so you can mess with movement to see what I mean. Controls with the mouse, WASD moves you relative to the player, space to reset if you lose track of the player.