- Home /
Question by
TrickShot_Lord · Sep 23, 2018 at 12:25 PM ·
addforcemouseposition
AddForce to mouse position
void FixedUpdate()
{
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var mouseDir = mousePos - gameObject.transform.position;
mouseDir.z = 0.0f;
mouseDir = mouseDir.normalized;
if (Input.GetKey(KeyCode.W))
{
rb.AddForce(mouseDir * speed);
}
if (Input.GetKey(KeyCode.A))
{
rb.AddForce(mouseDir * turnLeftSpeed);
}
if (Input.GetKey(KeyCode.D))
{
rb.AddForce(mouseDir * turnRightSpeed);
}
}
when I use this method to move my player to mouse direction It wont add force to its current position for example when the players position changed it adds force from the camera center I am not sure if I could explain it right but any kind of help will be okay thank you
Comment
Answer by LCStark · Sep 23, 2018 at 03:53 PM
Try this:
var mousePos = Input.mousePosition;
mousePos.z = 10.0f;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
var mouseDir = mousePos - gameObject.transform.position;
mouseDir.z = 0.0f;
mouseDir = mouseDir.normalized;
By default, the z
coordinate in Input.mousePosition
is always equal 0 and that gives weird results when you transform screen coordinates to world coordinates.
Answer by Vardanchik · Dec 20, 2020 at 08:58 AM
Here's My Version:
if(Input.GetMouseButtonDown(0)){
this.GetComponent<Rigidbody>().velocity = Vector3.zero;
Vector3 screenPoint = Camera.main.WorldToScreenPoint(transform.position);
Vector3 direction = (Vector3)(Input.mousePosition-screenPoint);
direction.Normalize();
this.GetComponent<Rigidbody>().AddForce(direction*10, ForceMode.Impulse);
}