- Home /
Idk what's wrong with my code..
So, I made a script that would make my player look at the mouse.position if you held down left click, and that function works fine. I also made it so when you lifted the mouse button it would launch. No matter what I do, it will keep moving up in world space, but I need it in local space. Heres my code:
private void LookAtMouse() {
if (_charging) {
Vector3 _mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
direction = new Vector3(_mousePosition.x - transform.position.x, _mousePosition.y - transform.position.y,0);
transform.up = direction;
} else {
//transform.rotation = Quaternion.Euler(0,0,0);
}
}
private void Launch() {
Debug.Log(_launchMultiplier);
if (Input.GetMouseButtonDown(0)) {
_anim.SetTrigger("Charge");
_charging = true;
StartCoroutine(PowerLaunch());
} else if (Input.GetMouseButtonUp(0)) {
_anim.SetTrigger("Launch");
_rb.AddForce(transform.up * launchSpeed * _launchMultiplier);
_charging = false;
_launchMultiplier = 0;
}
}
I think you may need to rephrase that last sentence, I just don't understand what you mean.
Answer by Bunny83 · Jul 22, 2018 at 10:33 PM
Well this boils down to some important counter questions:
Do you use a perspective camera or an ortographic camera? If you use a perspective camera your "ScreenToWorldPoint" would always return the camera position since you implicitly pass 0 as z distance
Where and when do you actually call your "LookAtMouse" method? Inside your Launch method you use the current up vector to add a force to the rigidbody. Keep in mind that once the force has been added any change of the object direction won't have any effect on the direction it's moving. Rigidbody physics is always simulated in worldspace. So it's velocity is a worldspace vector that is independent of the orientation of the object.
Finally what have you actually done yourself to debug your issue? Have you tried printing the vector that you use when you add the force? What direction do you get?
Hi, thanks so much! I didn't know tat rb physics are in worldspace. I ended up not using addforce, and I just changed the transform.position directly. Now it works great. Thanks!