- Home /
Player rotating after wall collision
Hello,
I have a game in which the player can Press W to move forward and A & D to rotate. Tthe problem I have is that once it hits a wall on it's side it starts rotating uncontrollably until i hit it again on the front. Please help if you can, im open to everything. Here is my movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour {
public Rigidbody2D player;
public float speed;
public float rotSpeed;
public GameObject wall;
public float delay;
private bool movementEnabled = true;
// Use this for initialization
void Start () {
player = GetComponent<Rigidbody2D>();
wall = GetComponent<GameObject>();
}
IEnumerator timeDisabled ()
{
yield return new WaitForSeconds(delay);
movementEnabled = true;
}
void OnCollisionEnter2D(Collision2D wall)
{
movementEnabled = false;
StartCoroutine("timeDisabled");
}
void RotateLeft()
{
transform.Rotate(Vector3.forward * rotSpeed);
}
void RotateRight()
{
transform.Rotate(Vector3.back * rotSpeed);
}
void move()
{
if (Input.GetKey(KeyCode.W))
{
player.velocity = (transform.up * speed);
}
else
{
player.velocity = new Vector2(0, 0);
}
if (Input.GetKey(KeyCode.A))
{
RotateLeft();
}
if (Input.GetKey(KeyCode.D))
{
RotateRight();
}
}
// Update is called once per frame
void Update () {
if (movementEnabled == true)
{
move();
}
else
{
}
}
}
Thank you!
Answer by OneCept-Games · Jan 02, 2018 at 04:33 PM
There are some different ways to solve this, but since you are modfying your object directly on the Transform while using Physics/Rigidbody velocity, try just changing the Update() to FixedUpdate() or LateUpdate(). You should consider using only physics (simple, but less in control), or only direct transformation and your own Ray cast collision (advanced, but more in control).
Changing the Update didn't work for me, and since this is my first game i don't think i can manage with doing Ray cast collisions. Is there any other way, because i'm running low on options?
Fully understand. Try to use physics methods on RigidBody to rotate your object, like AddTorque, Rotate, etc.
Your answer
Follow this Question
Related Questions
collision with wall so player dies 1 Answer
Detecting collision on start in my building system 0 Answers
Collision between Player and a Wall 2 Answers
Only sideways colliding detection 2 Answers
stop player when it hits a wall 2d 0 Answers