Reputation: 21
In unity, I am using ScreenToWorldPoint to move my object with my mouse, but the DrawRay from my transform to the ScreenPoint returns behind my camera for some reason. I've tried testing and finding out the reason but I just have no idea; here is my code:
using UnityEngine;
using System.Collections;
public class ScreenToWorldPointTest : MonoBehaviour {
public GameObject obj;
public Vector3 objDist;
public Vector3 objDistFwd;
public float moveSpeed = .1f;
void Start() {
obj = GameObject.Find("ChessKnightWhite");
}
void Update() {
Vector3 objPos = obj.transform.position;
objDist = objPos - transform.position;
objDistFwd = new Vector3(objDist.x * transform.forward.x, objDist.y * transform.forward.y, objDist.z * transform.forward.z);
Vector3 screenPoint = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, objDistFwd.magnitude)
Vector3 move = Vector3.lerp(screenPoint, transform.position, moveSpeed);
Debug.DrawRay(transform.position, screenPoint, Color.Green);
if(Input.GetMouseButton(0)) {
obj.transform.position = move - new Vector3(0, .5f, 0);
}
}
}
and usually, this works fine; the ray ends at the object (well, not at the object if it's being moved, but if it (the mouse) is still it would be at the object) and the object moves whenever and wherever I want it to, keeping the same distance from me (forwardly, where it's not the same distance but, say, the transform is normal (0, 0, 1), it will stay at 1 on the z-axis). But sometimes (observed at camera/player is at 0, 15, -10 -- with a rotation of 60 on the x -- and the object is at 0, 1, 0) the ray is behind me! and what's even weirder, is instead of going to where the Ray ends, it stays a little bit in front of the camera?! I thought, "maybe the z on ScreenToWorldPoint is negative?", but it cant be, because the x, z, and y are squared and added together to get magnitude. and printing it out even confirms this, but for some reason, it changes when I move the mouse sometimes. I have no idea what's causing this, so any insight would be very helpful (please also, if you can, include an explanation or any information as to why this might happen).
Upvotes: 0
Views: 612
Reputation: 21
so after a while I realized that Pluto was right, I needed to use dot product instead of the magnitude of (xa * xb, ya * yb, za * zb). Sorry Pluto, thanks for your help and your patience with me
Upvotes: 1