Hi,
I am kinda new to unity and I’m working on a little 3D game in which the character has to move thanks to “keywords” in a text box such as “move” “turnleft” etc… (Textboxes are replaced by buttons temporarily)
I need the character to move from a cube to another only, if I click the button on the left, it has to go to the blue cube in front of him.
I’ve got this code from now :
So yes, it’s going forward but toooo quickly…
I’ve tried using Time.deltaTime in the transform.translate(); but then when I press the button, the characters goes forward for like 1/100 of the wanted distance…
Have you got any solution to either slow down the tranform.translate and make the animation “seeable” or to use MoveTowards ? ( I used it aswell but it teleported too)…
by the way : I’m using Ethan, an included character in Unity
Also take note that transform.Translate and Vector3.MoveTowards must be used in Update() or Coroutine i think, otherwise it will move only one frame before it stops.
Hey,
Thanks for your answer !
It works fine with animation now, there is still a remaining problem, the character won’t stop walking when it is facing “x axis” (I mean Rotation 0,90,0). Have you got any tips ?
Here are the things I made (Thanks to you) :
(The currentPos var is updated in update() )
public IEnumerator GoForward()
{
var speed = 1.0f;
Vector3 futurePos = new Vector3(1.0f,0,0); //the var that contains the position for the character to go
//if looking at the right (+x axis)
if (transform.rotation == Quaternion.Euler(0, 90, 0))//I think this is where it doesn't work
{
futurePos = new Vector3(currentPos.x+1.0f, currentPos.y, currentPos.z);
}
//if looking at us (-z axis)
else if (transform.rotation == Quaternion.Euler(0, -180, 0) || transform.rotation == Quaternion.Euler(0, 180, 0))
{
futurePos = new Vector3(currentPos.x, currentPos.y, currentPos.z - 1.0f);
}
//if looking at the left (-x axis)
else if (transform.rotation == Quaternion.Euler(0, -90, 0))//here too aswell...
{
futurePos = new Vector3(currentPos.x - 1.0f, currentPos.y, currentPos.z);
}
//if it's turning back to us(+z axis)
else if (transform.rotation == Quaternion.Euler(0, 0, 0))
{
futurePos = new Vector3(currentPos.x, currentPos.y, currentPos.z + 1.0f);
}
while (Vector3.Distance(futurePos, m_Character.transform.position) > .1f)
{
m_Character.transform.position = Vector3.MoveTowards(m_Character.transform.position, futurePos, speed * Time.deltaTime);
m_Character.m_Animator.SetFloat("Forward", 1, 0.0f, Time.deltaTime);
yield return null;
}
}
Here is the function launched on click, as you advised me :
public void lancerMarche()
{
StartCoroutine(GoForward());
}
How do you set rotation ? Do you use transform.rotation = Quaternion; or slerp etc ? Try using <= and >= instead of ==. Also it may be easier to compare single axis instead of quaternions, like transform.rotation.x == x and so on.