Object Teleport given a radius and direction
I have found myself struggling with what I thought would be a simple mechanic to implement. I want my player to have an "evade" action, where if they press the key mapped to the "Evade" axis, they teleport at max 5 units towards the mouse cursor. The first part works, which is teleporting to the mouse position if within 5 units. Here is the code for reference.
The next part is what I am struggling with. I am trying to get the angle between the player and the mouse cursor, which is working fine. I then turn the angle to radians using Mathf.DegToRad. Then I make a new Vector 2 with the x and y being the Cos and Sin of the angle, respectively. This is where I think things are going wrong, but I'm not sure of why or how to fix it. Any help would be appreciated. Reference code below.
Notes: The game is top-down 2.5D, hence the vector2 to vector3 translation. evadeCount irrelevant to question.
Answer by Hellium · Jun 01, 2019 at 01:50 PM
Can't you simply do
Vector3 mousePosition = new Vector3( Input.mousePosition.x, Input.mousePosition.y, 10f );
mousePosition = Camera.main.ScreenToWorldPoint( mousePosition ) ;
Vector3 deltaPosition = mousePosition - transform.position;
evadeCount = ( deltaPosition .sqrMagnitude <= 25 ) ? evadeCount + 1 : 11;
transform.position += deltaPosition.ClampMagnitude( 5 ) ;
(This code is meant to replace all your if/else
piece of code)
That is exactly what I was looking for! Thank you! Looking up the Clamp$$anonymous$$agnitude API right now. Any idea why the previous Cos/Sin didn't work? If not then no worries, I'm just curious.
I believe there were 2 issues (not sure though):
Vector2.Angle
returns the unsigned acute angle between the two vectors. This means the smaller of the two possible angles between the two vectors is used.You were assigning a world position to
transform.position
ins$$anonymous$$d of translating the transform based on its previous position
Your answer
Follow this Question
Related Questions
how to teleport an object,want to teleport an object but it won't work 1 Answer
need help teleporting an object 0 Answers
Why does my enemy teleport to my player? 2 Answers
Teleporting To Projectile Location 1 Answer
Script for teleport on collision? 2 Answers