- Home /
transform.forward not always forward?
I have coded a "Dash" co-routine it's very simple. It's using a start point and an end point. The "end point" is calculated as "transform.forward * dash distance"
Vector3 dashStartPoint = transform.position;
Vector3 dashEndPoint = transform.forward * dashDistance;
float dashMovePercent = 0;
while (dashMovePercent < 1) {
dashMovePercent += dashSpeed * Time.deltaTime;
Vector3 position = Vector3.Lerp (dashStartPoint, dashEndPoint, dashMovePercent);
transform.position = position;
yield return null;
}
Any other tips or problems with these calculations would be appreciated. By the way I use a rigidbody for general movment and as the co-routine starts I set the state to "Dashing" and the player can't do any general movment (with the right stick btw).
It should be noted that sometimes the dash goes in the right direction other it can go in some strange directions.
Regards and thanks in advance Keagan
Answer by Bunny83 · Apr 28, 2017 at 03:08 PM
transform.forward is a direction vector with the length 1.0. It's not a point in space. You would need to do:
Vector3 dashStartPoint = transform.position;
Vector3 dashEndPoint = dashStartPoint + transform.forward * dashDistance;
ps: Not many people seem to use a for loop in such cases, but to me it always seems to look cleaner:
Vector3 dashStartPoint = transform.position;
Vector3 dashEndPoint = dashStartPoint + transform.forward * dashDistance;
for(float t = 0f; t < 1f; t += Time.deltaTime * dashSpeed)
{
transform.position = Vector3.Lerp (dashStartPoint, dashEndPoint, t);
yield return null;
}
Thanks @Bunny83 I realized earlier on today that that was the problem. I didn't realize at first since I would always just hit play and the player would dash from the origin so i didn't even noticed. Thanks. That would've been exactly the answer I was looking for but I gave up waiting because I am still a newbie and my questions take hours to get moderated.
Answer by Igor_Vasiak · Apr 28, 2017 at 12:43 PM
Try this:
private bool dash;
private float speed = 120000;
private Rigidbody rbody;
void FixedUpdate ()
{
rbody = GetComponent<Rigidbody>();
rbody.velocity = new Vector3(0, rbody.velocity.y, 0);
if (Input.GetKeyDown(KeyCode.E))
dash = true;
if (Input.GetKeyUp(KeyCode.E))
dash = false;
if (dash)
AddForce(transform.forward * speed * Time.fixedDeltaTime, ForceMode.Impulse);
}
Hope this helps!
This kind of solves the solution in a different way but it was definitely not an answer to the question that I posted. Thank you anyway @Galahad_Hohan!
Your answer
Follow this Question
Related Questions
Issue with Instantiate and the instant that spawns on a moving object that rotates 1 Answer
Rigidbody set velocity on 1 axis without changing the others. 5 Answers
Help making orbiting planets,How to rotate around the objects with the largest mass? 0 Answers