Unity中实例化GameObject朝鼠标方向匀速移动功能异常:速度受鼠标与玩家距离影响的问题排查
Fixing Variable Speed Issue for 2D Projectile Movement Towards Mouse Direction
Let's break down why your current code has variable speed, then fix it step by step:
What's Causing the Variable Speed?
You've got two key issues here:
- Incorrect Velocity Calculation:
Rigidbody2D.velocityrepresents distance per second, so multiplying byTime.deltaTimeis wrong. This turns a per-second speed into a per-frame movement value, making your speed dependent on frame rate and way larger than intended. - 3D Rotation API Misused in 2D:
Quaternion.LookRotationis designed for 3D spaces, so it points your object along the Z-axis (not the XY plane direction of your mouse). This meanstransform.forwardisn't the direction you actually want to move in, which messes up both rotation and speed behavior.
Fixed Code
private IEnumerator Rake() { // Get mouse position in world space, lock Z-axis to match the player's plane Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); mouseWorldPos.z = transform.position.z; // Calculate normalized direction from player to mouse (constant direction vector) Vector3 moveDirection = (mouseWorldPos - transform.position).normalized; // Calculate 2D rotation to face the mouse direction float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg; Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward); // Spawn the object with correct rotation GameObject WcastRB = Instantiate(Wcast, transform.position, rotation); Rigidbody2D rg = WcastRB.GetComponent<Rigidbody2D>(); // Set constant movement speed (adjust 5f to your desired units per second) float moveSpeed = 5f; rg.velocity = moveDirection * moveSpeed; // Wait 2 seconds, then stop movement yield return new WaitForSeconds(2f); rg.velocity = Vector2.zero; }
Key Fixes Explained:
- Z-Axis Lock: Ensures the mouse position calculation stays on the same plane as your player, avoiding weird depth-related direction errors.
- 2D-Specific Rotation: Uses
Mathf.Atan2to calculate the correct angle in the XY plane, thenQuaternion.AngleAxisto rotate the object to face that direction. - Proper Velocity Setup: Assigns a constant speed (units per second) directly to
velocity—noTime.deltaTimeneeded here. The normalized direction vector ensures movement speed stays consistent regardless of how far the mouse is from the player. - Simplified Coroutine Logic: No need to loop every frame to update speed; set it once, wait 2 seconds, then halt movement cleanly.
Quick Notes:
- Make sure your
Wcastprefab'sRigidbody2DhasGravity Scaleset to 0, otherwise gravity will pull the object off-course. - Adjust the
moveSpeedvalue (currently 5f) to make the object move faster or slower as needed.
内容的提问来源于stack exchange,提问作者Lee Geng
相关产品推荐
相关产品推荐

