Quantcast
Channel: Questions in topic: "enemy"
Viewing all articles
Browse latest Browse all 1488

Lock onto a target

$
0
0
My current code is below. I am wondering if there is a way for me to lock onto a target? I have tried transform.lookat(target) when button is pressed but the character doesn't stay looking at the target - have i done something wrong with the move function? What I am hoping for is when i hold A button my character looks at the target and moves whilst constantly looking at the target public class Controller : MonoBehaviour { [SerializeField] public float moveSpeed = 25.0f; //Change in inspector to adjust move speed Vector3 forward; Vector3 right; // Keeps track of our relative forward and right vectors void Start() { forward = Camera.main.transform.forward; // Set forward to equal the camera's forward vector forward.y = 0; // make sure y is 0 forward = Vector3.Normalize(forward); // make sure the length of vector is set to a max of 1.0 right = Quaternion.Euler(new Vector3(0, 90, 0)) * forward; // set the right-facing vector to be facing right relative to the camera's forward vector } void Update() { if (Input.GetAxis("Horizontal") != 0.0f && Input.GetAxis("Vertical") != 0.0f || Input.GetAxis("Horizontal") != 0.0f || Input.GetAxis("Vertical") != 0.0f) { Move(); // only execute if a key is being pressed } if (Input.GetButtonDown("A_Button_Mac") || Input.GetKeyDown("joystick button 0")) { Debug.Log("A button pressed"); //LOCK ONTO TARGET } } void Move() { Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); // setup a direction Vector based on keyboard input. GetAxis returns a value between -1.0 and 1.0. If the A key is pressed, GetAxis(HorizontalKey) will return -1.0. If D is pressed, it will return 1.0 Vector3 rightMovement = right * moveSpeed * Time.deltaTime * Input.GetAxis("Horizontal"); // Our right movement is based on the right vector, movement speed, and our GetAxis command. We multiply by Time.deltaTime to make the movement smooth. Vector3 upMovement = forward * moveSpeed * Time.deltaTime * Input.GetAxis("Vertical"); // Up movement uses the forward vector, movement speed, and the vertical axis inputs. Vector3 heading = Vector3.Normalize(rightMovement + upMovement); // This creates our new direction. By combining our right and forward movements and normalizing them, we create a new vector that points in the appropriate direction with a length no greater than 1.0 transform.forward = heading; // Sets forward direction of our game object to whatever direction we're moving in transform.position += rightMovement; // move our transform's position right/left transform.position += upMovement; // Move our transform's position up/down } }

Viewing all articles
Browse latest Browse all 1488

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>