2 Hours Research
2 Hours Code/Assets
After several hours of playing with codes and figuring out how rays work I created a new movement system for the spaceship. It now turns to where ever the mouse is pointing, all I need now is a way to make it slow down. I know of one method Quaternion.Slerp but I cannot get it to work. The movement part of the system uses a force multiplier system, if you use drag and angular drag on the ridged body it accounts for a autoslow and max speed system. Its not the best but it will do for now.
Add a new layer, call it "Floor" change the background to the layer Floor.
Add to top variables
//Movement Variables
Rigidbody playerRigidbody; // Reference to the player's rigidbody.
int floorMask; // A layer mask so that a ray can be cast just at gameobjects on the floor layer.
float camRayLength = 1000f; // The length of the ray from the camera into the scene.
Vector3 rotationFix = new Vector3(0, 0, 0);
public float movementSpeed = 5.0f;
Add Awake to the top Clear out Fixed update and add
void Awake ()
{
// Create a layer mask for the floor layer.
floorMask = LayerMask.GetMask ("Floor");
// Set up references.
playerRigidbody = GetComponent <Rigidbody> ();
}
// Transform direction is dependant on what angle you are using.
void FixedUpdate () // FixedUpdate runs with physics
{
if (Input.GetKey(KeyCode.W))
{
playerRigidbody.AddForce(transform.up * movementSpeed);
}
else if (Input.GetKey(KeyCode.S))
{
playerRigidbody.AddForce(transform.up * movementSpeed);
}
else if (Input.GetKey(KeyCode.A))
{
playerRigidbody.AddForce(-transform.forward * movementSpeed);
}
else if (Input.GetKey(KeyCode.D))
{
playerRigidbody.AddForce(transform.forward * movementSpeed);
}
// Turn the player to face the mouse cursor.
Turning();
// Animate the player.
}
void Turning()
{
// Create a ray from the mouse cursor on screen in the direction of the camera.
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
// Create a RaycastHit variable to store information about what was hit by the ray.
RaycastHit floorHit;
// Perform the raycast and if it hits something on the floor layer...
if (Physics.Raycast(camRay, out floorHit, camRayLength, floorMask))
{
// Create a vector from the player to the point on the floor the raycast from the mouse hit.
Vector3 playerToMouse = floorHit.point - transform.position;
// Ensure the vector is entirely along the floor plane. Axis must be the only one not being used by the player to move in.
playerToMouse.z = 0f;
// Create a quaternion (rotation) based on looking down the vector from the player to the mouse.
Quaternion newRotatation = Quaternion.LookRotation(playerToMouse);
//Quaternion.Euler is to correct for the 2d angle.
newRotatation *= Quaternion.Euler(90, 0, 0);
// Set the player's rotation to this new rotation.
playerRigidbody.MoveRotation(newRotatation);
}
}
No comments:
Post a Comment