Hi,
I’m posting there a script which isn’t optimized and not working at all, this script needs of a rigidbody2d attached to the gameobject.
The issue I’ve discovered is the following:
when you press first right ( or left ) and then the opposite ( left or right, it depends ) the gameobject has the double velocity that it has at the beginning. Someone Could help me to explain what am I doing wrong?
using UnityEngine;
using System.Collections;
public class PlayerEngineRigidBody : MonoBehaviour
{
private float walkSpeed;
private float runSpeed;
private float curSpeed;
private CharacterStat plStat;
void Start() // because have to take the value of agility and speed
{
plStat = GetComponent<CharacterStat>();
walkSpeed = (float)(plStat.Speed + plStat.Agility);
runSpeed = walkSpeed + (walkSpeed / 2);
}
void Update()
{
// penso funzioni, usare debug script per sicurezza... ( possibilità di effetto placebo )
curSpeed = walkSpeed;
if (Input.GetAxis ("Sprint") > 0) {
curSpeed = runSpeed;
}
// Brake Sentences
if (Input.GetAxis ("Left") == 0 || Input.GetAxis ("Right") == 0 )
{
rigidbody2D.velocity = Vector3.Lerp(rigidbody2D.velocity, new Vector2(0f, rigidbody2D.velocity.y), 0.15f);
}
if (Input.GetAxis ("Up") == 0 || Input.GetAxis ("Down") == 0)
{
rigidbody2D.velocity = Vector3.Lerp(rigidbody2D.velocity, new Vector2(rigidbody2D.velocity.x, 0f), 0.15f);
}
// Move senteces
if (Input.GetAxis ("Left") < 0)
{
rigidbody2D.AddForceAtPosition (Vector3.right * Input.GetAxis ("Left") * curSpeed, transform.position);
}
if (Input.GetAxis ("Right") > 0)
{
rigidbody2D.AddForceAtPosition (Vector3.right * Input.GetAxis ("Right") * curSpeed, transform.position);
}
if (Input.GetAxis ("Down") < 0)
{
rigidbody2D.AddForceAtPosition (Vector3.up * Input.GetAxis ("Down") * curSpeed, transform.position);
}
if (Input.GetAxis ("Up") > 0)
{
rigidbody2D.AddForceAtPosition (Vector3.up * Input.GetAxis ("Up") * curSpeed, transform.position);
}
}
}