Next, I want to press and let go of the Space Bar to make the bullet Lerp between two positions.
example: Vector3 positionA = new Vector3 (0, 3, 0);
Vector3 positionB = new Vector3 (0, -3, 0);
if (Input.GetKey (KeyCode.Space)){
newPosition = positionB;
}
if (Input.GetKeyUp (KeyCode.Space)) {
newPosition = positionA;
}
transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime);
That works fine, except the bullet no longer moves forward, because of the “0’s” in the “new Vector3”
May I please, please ask for your help? Is there a way to keep the bullet moving, while using Lerp to just affect the Y-axis? Thank you for reading this, either way
Be advised that the correct way to use Lerp is:
current = Lerp(start, end, (zero-to-one) )
You’re currently using the form:
current = Lerp(current, end, (small number) )
The latter will give you a sort of “smooth snap” effect, while Lerp ought to be giving you a “direct line” effect. I rather like the latter form for camera movements, but it’s wrong for most other purposes. In this case, you can use Vector3.MoveTowards to get a “direct line” effect without knowing the start and end positions from the beginning.
As for the main issue you’re having, you can set your Vector3 to the existing position value, and then inject a new number into the Vector3 to use for its position.
Additional bonus tip: you can use a ternary operator if your “if…then…else” logic only changes one variable in the logic. It looks like: int finalResult = (someCondition ? resultIfTrue : resultIfFalse);
The bullet still doesnt move forward on its own. It moves forward a little bit on pressing SpaceBar, but I want the bullet to move on its own. The code you gave me is, however, a step closer It replaces Lerp better than I imagined, and Im very thankful for that! Thank you for helping me!!
The bullet does not move in any direction, unless the Space Bar is pressed.
Thank you for the operator information!! I will definitely put that into practice
Its in Update. I tried FixedUpdate, too. Dont get me wrong, both pieces of code work perfect individually. Having them both active is what causes the bullet to stay still (it does twitch between 4.8 and 5 on the Z-axis like its trying to go foward)
With just the top code: the bullet moves forward
With just the bottom code, the bullet moves up and down
With both, your code works (it moves up and down), and my code doesnt work (the moving forward one)
Thank you, either way! Ive learned something very applicable, already!!
Where do you set the value of newPosition? If you set it before you call rigidbody.MovePosition, it will be basing that on the previous position and won’t move forward.
Youre Right!!! I had newPosition in Awake (); You resolved my issue without even seeing that in the code. You are smart! Thank you for helping me. Now, if you can just stay here forever, and teach me to code^.^ just kidding! Thank you, friend!!!