After adding a force to a moving gameobject it will behaviour in a strange way.
i have a game object with a velocity (rb.velocity.x,rb.velocity.y,10) set at start.When this objectcollides with another one that has an especific tag (curva) i make that game object turn by rotating it and adding relative forcé forwar.This makes object go too much forward, for compensate that i also add a global backward force. This works well, but when the gameobject exit the collider, it start moving diagonal with no evident cause. I am a newbie, so i dont know how to solve that, thank you for your help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class sCRIPT : MonoBehaviour {
private Rigidbody rb;
Vector3 turn = new Vector3 (0,-0.6f,0);
public GameObject h;
public float moveHorizontal;
public float test;
float inturn = 1;
public float crash = 0;
public float zVel;
public float pos;
void Start () {
test = 0;
rb = GetComponent<Rigidbody>();
rb.freezeRotation = enabled;
rb.velocity = new Vector3 (rb.velocity.x,rb.velocity.y,-20);
}
void FixedUpdate ()
{
if (crash == 0) {
moveHorizontal = Input.GetAxis ("Horizontal");
Vector3 movement = new Vector3 (moveHorizontal * inturn, 0, 0);
rb.AddRelativeForce (movement * -10);
}
if (test == 1) {
transform.Rotate (turn);
rb.AddRelativeForce (new Vector3 (0, 0, -20));
rb.AddForce (new Vector3 (0, 0, ((-zVel) - 5)), ForceMode.Acceleration);
}
if (transform.eulerAngles.y != 0) {
if (transform.eulerAngles.y <= 270) {
test = 0;
}
}
zVel = (transform.position.z-pos)/Time.fixedDeltaTime;
pos = transform.position.z;
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.Space)) {
rb.velocity = new Vector3 (rb.velocity.x, 11, rb.velocity.z);
}
}
void OnTriggerEnter (Collider other){
if (other.gameObject.CompareTag ("curva")) {
inturn = 1.5f;
test = 1;
}
}
void OnCollisionStay(Collision other){
if (other.gameObject.CompareTag ("pared")) {
crash = 1;
}
}
void OnTriggerExit (Collider other){
if (other.gameObject.CompareTag ("curva")) {
inturn = 1;
test = 0;
}
}
void OnCollisionExit (Collision other){
if (other.gameObject.CompareTag ("pared")) {
crash = 0;
}
}
}
Your answer
Follow this Question
Related Questions
How to apply a force at certain point of an object? 0 Answers
Space,Gravity,RigidBody,Physics Forces 0 Answers
How to calculate force applied to gameObject? 0 Answers
How do I get objects in front of the player to be blasted away? 1 Answer
Getting two Objects to the same direction with different speed 0 Answers