I am making my first game and it involves moving a space ship around. I am happy with my primary movement scripting sans how it strafes. The object constantly turns to face the mouse pointer, which gives a great method for aiming, and moving the ship about. However, it does constrain how I handle strafing.
I have played with two lines of code each one has benefits, but doesn’t quite do what I want. The entire code is included at the bottom. Nothing is particularly original, I am building what I learned in doing a handful of tutorials, and trying to build something of my own using what I have learned.
rb.AddForce(gameObject.transform.right * strafespeed * h);
This line works pretty well, but the ship strafes around my mouse pointer, giving weird circular movement that doesn’t work well for my level design.
transform.position += new Vector3(strafespeed * h, 0, 0);
Using this line makes the strafing behave more like I am looking for, it moves it directly across the X axis, however I lose the natural feel of the rb.AddForce for the strafing movement. The glide that makes the ship feel like it is operating without much friction.
I am hoping to find some combination that lets me use the rb.Addforce on my player object but relative to the global space, not relative to the player gameobject. I am not sure if that is doable, I am still learning.
Full Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Boundary
{
public float xMin, xMax, yMin, yMax;
}
public class PlayerController : MonoBehaviour {
public Boundary boundary;
//Navigation Variables
public float speed;
public float strafespeed;
//Weapon Variables
public Transform shotSpawn1;
public Transform shotSpawn2;
public GameObject shot;
public float fireRate;
private float nextFire;
private Rigidbody2D rb;
void Start ()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update ()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSpawn1.position, shotSpawn1.rotation);
Instantiate(shot, shotSpawn2.position, shotSpawn2.rotation);
}
}
private void FixedUpdate()
{
var mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Quaternion rot = Quaternion.LookRotation(transform.position - mousePosition, Vector3.forward);
transform.rotation = rot;
transform.eulerAngles = new Vector3(0, 0, transform.eulerAngles.z);
float v = Input.GetAxis("Vertical");
float h = Input.GetAxis("Horizontal");
rb.AddForce(gameObject.transform.up * speed * v);
rb.AddForce(gameObject.transform.right * strafespeed * h);
//transform.position += new Vector3(strafespeed * h, 0, 0);
rb.position = new Vector3
(
Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax),
Mathf.Clamp(rb.position.y, boundary.yMin, boundary.yMax),
0.0f
);
}
}