I have a Character with these components:
SpriteRenderer
Rigidbody2D
Circle Collider
Box Collider
PlayerController script (where all the magic happens)
And for some reason with the code I have below, whenever my sprite makes it to the location it just vanishes from the screen. I think it has something to do with me not accounting for the Camera perspective, and I don’t think it has to do with all the components above since I added a new GameObject with just the SpriteRenderer component and the script, but the same problem persisted.
Using the Debug.Log() the coordinates all work out, the only thing that is off is that the initial location is Vector3(0,0,0) for the sprite, and the z-location goes to -10 so I’m not sure if that is having an affect.
There is absolutely nothing else in the scene, and my sprite just vanishes once the sprite vector = mouse click location. Also the Debug.Log() shows that if I click again with the image gone, the coordinates are still updating.
Sorry for all the comment lines, I thought maybe leaving them in would help give others insight to my train of thought and see where I was going wrong on this. Any and all advice is appreciated! Still new to Unity, if it’s not obvious. I’ve also tried leaving this portion of code
transform.position = Vector3.MoveTowards(transform.position, pos, speed);
in the update call, but the same error happens.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed;
private Vector3 pos;
//private Vector3 cameraPos;
// Use this for initialization
void Start ()
{
pos = transform.position;
//cameraPos = Camera.main.WorldToViewportPoint(transform.pos);
speed = 0.1f;
Debug.Log(string.Format("START"));
}
// Update is called once per frame
void Update()
{
Movement();
}
/// <summary>
/// Check for Mouse input and if received move player towards the mouse coordinates
/// </summary>
void Movement()
{
if (Input.GetMouseButtonDown(0))
{
//This was part of the tutorial, I'm not sure why it's here.
// Leaving it here until game is complete to see if reasoning for it being here blossoms
//pos.z = -5.0f;
pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log(string.Format("Pushed!"));
}
// needs fixing, the movement is not smooth nor updateable with a simple value change for movement
if (transform.position != pos)
{
//Debug.Log(string.Format("NO"));
transform.position = Vector3.MoveTowards(transform.position, pos, speed);
}
else if (transform.position == pos)
{
//Debug.Log(string.Format("YES"));
}
Debug.Log(string.Format(transform.position.ToString() + "Char"));
Debug.Log(string.Format(pos.ToString() + "Mouse"));
if (Input.GetKeyDown(KeyCode.A))
{
transform.position = new Vector3(-0.2f, -2.1f, 0.0f);
pos = transform.position;
}
//cameraPos.x = Mathf.Clamp01(cameraPos.x);
//cameraPos.y = Mathf.Clamp01(cameraPos.y);
//transform.position = Camera.main.ViewportToWorldPoint(cameraPos);
}
}