- Home /
How can I make a character controller that changes positions on one click.
Hi everyone, How can I make a character controller that when a player clicks on the screen the character will move to a given position on the X Axis and when the player clicks the screen again the character will move back to its original position on the X Axis and that will just repeat when the player clicks continuously.
To make it clear there is only 2 specified position for the character for example:
The original position of the character on the X Axis is 1.65 when the player clicks the character will move to -1.65 and when the player clicks again it will move back to 1.65 and when clicks again will move again to -1.65. That's what i'm trying to do. Im using Input.GetMouseButtonDown(0).
Answer by HACFelipe · Oct 25, 2018 at 05:12 PM
First, you'll need to store the character original position, and the targeted position.
Then, you dynamically change the direction the character is moving to.
For example:
Vector2 GetCharPos()
{
return transform.position;
}
void Start()
{
cam = Camera.main;
oriPos = (0, 0);
newPos = (0, 0);
mousePos = Input.mousePosition;
targetPoint = (0, 0);
speed = 10.0f;
}
void Update()
{
if Input.GetMouseButtonDown(0)
{
if oriPos != (0, 0)
{
oriPos = GetCharPos();
targetPoint = oriPos;
}
newPos = cam.ScreenToWorldPoint(mousePos.x, mousePos.y);
targetPoint = newPos;
}
transform.position = Vector2.MoveTowards(transform.position, targetPoint, speed * Time.deltaTime);
}
Your answer
Follow this Question
Related Questions
Let Character Controller jump. 0 Answers
RigidBody Character Controller Bug 0 Answers
Rotate character controller on all axis 0 Answers
Let Character Controller jump. 1 Answer
CharacterController NullReferenceException dispite attached to object 1 Answer