- Home /
Adding multiple "global velocities" to an object
I don't know of any question that ask about adding multiple velocities to an object, but this might come in handy for a few game ideas if deciding to use it.
I am making a game project that involves the player shooting bullets from a rotating unit in a fast-moving car. The gist is that in addition to the bullets moving from the direction of the unit and its own speed, they should also move based on the velocity of the player. However, when trying out the implementation, it does not work as expected.
I will show you the following "velocities" added together to the bullet
Player Driver - The desired velocity from the driver object to be added to the bullet rb2d.velocity = tsfm.up * speedCurr; // used to get velocity of driver in current frame, including rotation
Bullet - Velocity of the bullet applied by default m_transformCache.position += m_transformCache.up * m_speed * deltaTime; // another way to update velocity
Component to add driver's velocity to the existing bullet gameObject:
// snapped velocity is retrieved from driver.tsfm.up * speedCurr // //gameObject.transform.Translate(m_snappedVelocity * Time.deltaTime); gameObject.transform.position += m_snappedVelocity * Time.deltaTime;
However, none of the previous solutions worked since the driver's velocity somehow screws up the vector when entering into opposing values.
Is there a way that I can add the two global velocity vectors based on a local object's direction vector so that the bullets can move with the player's velocity like bullets moving straight with a scrolling background? I would be very thankful if someone can give a clear answer to adding multiple velocities to any object like bullets.
Answer by MrJBRPG · Jul 25, 2017 at 02:37 AM
I solved it after a few hours of debugging it myself.
Apparently, it can be easily solved by first grabbing the individual parts with normalized vector / length 1 vectors (like tsfm.up) and speed float and then using whatever update suitable to combine them together.
Wrong Way
m_snappedVelocity = getObjectVelocity(); // Get object that has direction * scale but messes up on local axes gameObject.transform.position += m_snappedVelocity * Time.deltaTime;
Correct Way
objectDirection = getObjectDirection(); // can be used with transform.up, right, etc. objectSpeed = getObjectSpeed(); // get the float value for speed m_snappedVelocity = objectDirection * objectSpeed; // Now you get the correct velocity gameObject.transform.position += m_snappedVelocity * Time.deltaTime;
Your answer
Follow this Question
Related Questions
SImply yet tricky question about RELATIVE VELOCITIES... 1 Answer
Physics in 2d arkanoid. Tangential and normal velocity 1 Answer
Velocity Movement & Physics Interactions by Rigidbody2D 0 Answers
How to plot velocity of vehicle wheel collider on realtime graph 0 Answers
is there a way to check the path of a RigidBody.velocity? 1 Answer