- Home /
Object moves to bottom left of the canvas?
Hello, Im simply trying to get a click move feature to work, I have followed 2 YouTube videos and both times I have the same result , whilst theirs works perfectly of course.
Here is the script , the script results in the object moving to the same corner of the canvas each time, regardless of the click position, once there clicking again does nothing. Im thinking it has to just be something stupid that I have missed at this point so any help would be very much appreciated !
alt text
private float speed = 40;
private Vector3 targetPosition;
private bool isMoving = false;
void Update()
{
if (Input.GetMouseButton(0))
{
SetTargetPosition();
}
if (isMoving)
{
Move();
}
}
void SetTargetPosition()
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPosition.z = transform.position.z;
isMoving = true;
}
void Move()
{
transform.rotation = Quaternion.LookRotation(Vector3.forward, targetPosition);
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
if (transform.position == targetPosition)
{
isMoving = false;
}
}
}
Answer by sacredgeometry · Dec 30, 2020 at 06:37 PM
Try giving the ScreenToWorldPoint a properly formed Vector3. i.e.
targetPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 12));
Thanks for the answer, unfortunately the same results !
And A video (can skip the first few seconds)
And the same script inside a blank scene.
I am not sure what you have done because in a new scene, attaching this script to a cube seems to work.
using UnityEngine;
public class Tester : $$anonymous$$onoBehaviour
{
private float speed = 40;
private Vector3 targetPosition;
private bool is$$anonymous$$oving = false;
void Update()
{
if (Input.Get$$anonymous$$ouseButton(0))
{
SetTargetPosition();
}
if (is$$anonymous$$oving)
{
$$anonymous$$ove();
}
}
void SetTargetPosition()
{
targetPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 12));
is$$anonymous$$oving = true;
}
void $$anonymous$$ove()
{
transform.rotation = Quaternion.LookRotation(Vector3.forward, targetPosition);
transform.position = Vector3.$$anonymous$$oveTowards(transform.position, targetPosition, speed * Time.deltaTime);
if (transform.position == targetPosition)
{
is$$anonymous$$oving = false;
}
}
}
Your answer
Follow this Question
Related Questions
Change sprite when moving(2D) 1 Answer
Question on Sprite and Movement 0 Answers
Simple movement problem. Need units to stop dead on collision. 3 Answers
How to prevent jitter with movement over curved slopes 0 Answers
Player moves to the middle of the room when the level starts (2d point and click) 2 Answers