- Home /
How to correctly throw object from enemy to main character in Unity2D
I have two character in my game: enemy and main character. Enemy can throw different objects into the main character. For this moment i am doing this action in such way: void FixedUpdate(){ if (CanMove){ transform.position = Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 * Time.deltaTime); } }
public void StartMove(bool canMove){
CanMove = canMove;
TargetPlayer = GameObject.FindGameObjectWithTag(Tag).transform;
rigidbody2D.gravityScale = 0;
}
This script is attached to the prefab of the object that will be thrown into main character by the enemy. This script is working, but in this case the object that was thrown will follow by main character all the time, because of this line of code: **transform.position = Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime);*
To my mind this is not good, because i want to give my player the opportunity to escape from the object that was thrown at him. For example run away. When the object reaches the player position (and the player is on the new position) - he will simply fall onto the ground. I did this, but this wasn't looking nice, because when the object was reaching his position, he was hanging in the air. Can anyone give me an advice how to make this process more good-looking?
Answer by mansoor090 · Oct 09, 2018 at 10:34 AM
Oh no , no one replied at your post. I am facing the same problem right now. can you help me out. i am trying to build a similar game.
Just save the position at the beginning ins$$anonymous$$d of reading player position each frame.
Vector3 targetPosition = Vector3.zero;
private void FixedUpdate()
{
if (Can$$anonymous$$ove)
{
transform.position = Vector2.$$anonymous$$oveTowards(transform.position, targetPosition, 15 * Time.deltaTime);
}
}
public void Start$$anonymous$$ove(bool can$$anonymous$$ove)
{
Can$$anonymous$$ove = can$$anonymous$$ove;
TargetPlayer = GameObject.FindGameObjectWithTag(Tag).transform;
targetPosition = TargetPlayer.transform.position;
rigidbody2D.gravityScale = 0;
}
Your answer
Follow this Question
Related Questions
Profiler mystery with Physics2d 0 Answers
Disable weight "inheritance" when using HingeJoint2D? 1 Answer
Platformer2D Player sticks to platform corners 0 Answers
How can I slow the velocity of my player without it affecting fall speed? 0 Answers
increasing knockback of a rigidbody as received damage increases (like super smash) 1 Answer