Question by
Goubermouche · Feb 15, 2020 at 03:49 AM ·
collisioncontrollertank
Unity 3D rigidbody collision doesnt work correctly
hello i have recently started working on a pvp tank brawler and i ran into a problem: my controller (see below) is working perfectly apart from collisions - whenever my tank collides with anything else it starts to rotate and goes int a seemingly random direction. any help would be appreciated!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class controlls : MonoBehaviour
{
public int m_playerNumber = 1;
public float m_speed = 12f;
public float m_turnSpeed = 180f;
public AudioSource m_movementAudio;
public AudioClip m_engineIdle;
public AudioClip m_engineDriving;
public float m_PitchRange = 0.2f;
private string m_movementAxisName;
private string m_turnAxisName;
private Rigidbody m_rigidbody;
private float m_movementInputValue;
private float m_turnInputValue;
private float m_originalPitch;
private void Awake()
{
m_rigidbody = GetComponent<Rigidbody>();
}
private void OnEnable()
{
m_rigidbody.isKinematic = false;
m_movementInputValue = 0f;
m_turnInputValue = 0f;
}
private void OnDisable()
{
m_rigidbody.isKinematic = true;
}
private void Start()
{
m_movementAxisName = "Vertical" + m_playerNumber;
m_turnAxisName = "Horizontal" + m_playerNumber;
m_originalPitch = m_movementAudio.pitch;
}
private void Update()
{
m_movementInputValue = Input.GetAxis(m_movementAxisName);
m_turnInputValue = Input.GetAxis(m_turnAxisName);
EngineAudio();
}
private void EngineAudio()
{
if (Mathf.Abs(m_movementInputValue) < 0.1f && Mathf.Abs(m_turnInputValue ) < 0.1f)
{
if (m_movementAudio.clip == m_engineDriving)
{
m_movementAudio.clip = m_engineIdle;
m_movementAudio.pitch = Random.Range(m_originalPitch - m_PitchRange, m_originalPitch + m_PitchRange);
m_movementAudio.Play();
}
}
else
{
if (m_movementAudio.clip == m_engineIdle)
{
m_movementAudio.clip = m_engineDriving;
m_movementAudio.pitch = Random.Range(m_originalPitch - m_PitchRange, m_originalPitch + m_PitchRange);
m_movementAudio.Play();
}
}
}
private void FixedUpdate()
{
Move();
Turn();
}
private void Move()
{
Vector3 movement = transform.forward * m_movementInputValue * m_speed * Time.deltaTime;
m_rigidbody.MovePosition(m_rigidbody.position + movement);
}
private void Turn()
{
float turn = m_turnInputValue * m_turnSpeed * Time.deltaTime;
Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
m_rigidbody.MoveRotation(m_rigidbody.rotation * turnRotation);
}
}
Comment
@Goubermouche What are your rigidbody settings, and have you tried to increase the rotational drag value?
Your answer
Follow this Question
Related Questions
3D Jumping Collision Bug 1 Answer
Player pushes object but gets pushed into the Wall/Boundary 0 Answers
why my object pass through 0 Answers
Adding collisions to a custom character controller? 1 Answer