Hello!
I am trying to do a smooth movement in an 2D object, but I am having error, here is the script:
using UnityEngine;
using System.Collections;
public class Flutuar : MonoBehaviour {
public GameObject pontoPivo; //Objeto de referencia para a criação do diametro
public float minForça;
public float maxForça;
public float maxDistancia;
public float tempoRenovarForça;
private float fatorDeForça; //Variable that will receive the force
private float tempoCorrenteRenovar; //Time of influence of force
private float distanciaDoPivo; //Variable that measures the distance of the object to the pontoPivo
private Vector3 direçao; //Direction in which force is applied
private Rigidbody corpoRigido;
private bool novaDireçao; //Auxiliary variable to change the direction
void Start () {
corpoRigido = GetComponent();
novaDireçao = true;
}
void FixedUpdate () {
distanciaDoPivo = Vector3.Distance(transform.position, pontoPivo.transform.position);
//If my object is outside the diameter specified by the Spring Joint in the PontoPivo
if(distanciaDoPivo >= maxDistancia) {
//The direction of the force will be applied to the PontoPivo, thus returning to the diameter
fatorDeForça = Random.Range(minForça, maxForça);
tempoCorrenteRenovar = 0;
direçao = (pontoPivo.transform.position - transform.position).normalized; //.normalized e utilizado para pegar a direçao de um Vector3
fatorDeForça = Random.Range(minForça, maxForça);
}
//If my object is within the specified diameter
if(distanciaDoPivo < maxDistancia) {
//Counter to change the direction
tempoCorrenteRenovar += Time.deltaTime;
if(tempoCorrenteRenovar >= tempoRenovarForça) {
tempoCorrenteRenovar = 0;
novaDireçao = true;
}
//Random Direction
if(novaDireçao) {
direçao.x = Random.Range(-1f, 1f);
direçao.y = Random.Range(-1f, 1f);
fatorDeForça = Random.Range(minForça, maxForça);
novaDireçao = false;
}
}
//Objeto que receber a força
corpoRigido.AddForce(direçao * fatorDeForça - corpoRigido.velocity); /I had to do the “-corpoRigido.velocity” to keep…
} //…the speed of the object
}
My problem is exactly in the line “corpoRigido.AddForce(direçao * fatorDeForça - corpoRigido.velocity);”
If I remove the “- corpoRigido.velocity”, the error desappears, but I need of this line to mantain the velocity.
May someone sugest some correction to this error?