Unity 2D 5.2.2 How can I aim with keys towards an object?
Hello there,
It seems that nobody responded to my previous question, it also seems that it was a bit difficult to do then...
But I won't give up yet!
So, I wanted to ask how to make my main character (Titus) aim at a 'aim point' that I control separately.
So basically I want that 'aim point' to be controlled with the IJKL keys, but I want to move my Titus with WASD keys, and when I shoot a projectile, it is shot towards my 'aim point'.
here are my scripts in the following order : Mouse control and shoot and then the movement script of 'Titus'.
using UnityEngine;
using System.Collections;
public class BulletPrototype1 : MonoBehaviour
{
public float maxSpeed = 25f;
public GameObject Bullet;
private Transform _myTransform;
private Vector2 _lookDirection;
private void Start()
{
if (!Bullet)
{
Debug.LogError("Bullet is not assigned to the script!");
}
_myTransform = transform;
}
private void Update()
{
/*
mousePos - Position of mouse.
screenPos2D - The position of Player on the screen.
_lookDirection - Just the look direction... ;)
*/
// Calculate 2d direction
// The mouse pos
var mousePos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
// Player Camera must have MainCamera tag,
// if you can't do this - make a reference by variable (public Camera Camera), and replace 'Camera.main'.
var screenPos = Camera.main.WorldToScreenPoint(_myTransform.position);
var screenPos2D = new Vector2(screenPos.x, screenPos.y);
// Calculate direction TARGET - POSITION
_lookDirection = mousePos - screenPos2D;
// Normalize the look dir.
_lookDirection.Normalize();
}
private void FixedUpdate()
{
if (Input.GetButtonDown("Fire1"))
{
// Spawn the bullet
var bullet = Instantiate(Bullet, _myTransform.position, _myTransform.rotation) as GameObject;
if (bullet)
{
// Ignore collision
Physics2D.IgnoreCollision(bullet.GetComponent<Collider2D>(), GetComponent<Collider2D>());
// Get the Rigid.2D reference
var rigid = bullet.GetComponent<Rigidbody2D>();
// Add forect to the rigidbody (As impulse).
rigid.AddForce(_lookDirection * maxSpeed, ForceMode2D.Impulse);
// Destroy bullet after 5 sec.
Destroy(bullet, 5.0f);
}
else
Debug.LogError("Bullet not spawned!");
}
}
}
using UnityEngine;
using System.Collections;
public class PlayerMovement2 : MonoBehaviour {
Rigidbody2D PlayerBody;
Animator Animi;
void Start () {
PlayerBody = GetComponent<Rigidbody2D>();
Animi = GetComponent<Animator>();
}
void Update () {
Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (movement_vector != Vector2.zero)
{
Animi.SetBool("Walking", true);
Animi.SetFloat("Input_x", movement_vector.x);
Animi.SetFloat("Input_y", movement_vector.y);
}
else
{
Animi.SetBool("Walking", false);
}
PlayerBody.MovePosition(PlayerBody.position + movement_vector * Time.deltaTime);
}
}
Well, those are the two scripts. Can someone give me some help with this? I do not want a 'script that is already made for me' without information about how it works. I want an explanation about how to do it, instead of having it all done for me. Even though I am no great programmer I still want to try it myself! honestly I do not understand how I can make an object that my 'Titus' aims to. the movement of the object can be done simply, and I can change it in control config in unity game-play settings. The hard part is connecting those two, and make them work correctly.
If you want more information about what kind of game I am making, It is a 2-D top down platform game (not turn based if it is important to know), so there is no gravity, but there are physics like bouncing, walls, doors and mechanics. Thank you all in advance and have a nice day, Daniel Nowak Janssen
Answer by Statement · Nov 02, 2015 at 09:35 PM
I want that 'aim point' to be controlled with the IJKL keys, but I want to move my Titus with WASD keys, and when I shoot a projectile, it is shot towards my 'aim point'.
Ok..
public Transform aimPoint;
Mouse control and shoot
Wait, what? I thought you wanted to aim with IJKL? What else does mouse do than shoot? How many hands do you have, human?
Anyway, movement if aim is simple with IJKL, just set axis up in InputManager.
Vector3 aimAxis = new Vector3(Input.GetAxis("AimHorizontal"), Input.GetAxis("AimVertical"));
aimPoint.Translate(aimAxis * aimSpeed * Time.deltaTime);
If you want to get the direction and rotation to aimPoint, I have two helper classes.
namespace Answers
{
using UnityEngine;
public static class Directions
{
public static Vector2 FromTo2D(Vector2 from, Vector2 to)
{
return (from - to).normalized;
}
public static Vector2 FromTo2D(Transform from, Transform to)
{
return FromTo2D(to ? (Vector2)to.position : Vector2.zero,
from ? (Vector2)from.position : Vector2.zero);
}
}
public static class Rotations
{
public static Quaternion LookAt2D(Vector2 from, Vector2 to)
{
Vector2 diff = from - to;
float angle = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
return Quaternion.Euler(0, 0, angle);
}
public static Quaternion LookAt2D(Transform from, Transform to)
{
return LookAt2D(to ? (Vector2)to.position : Vector2.zero,
from ? (Vector2)from.position : Vector2.zero);
}
}
}
Then you can do something like...
bulletRotation = Answers.Rotations.LookAt2D(transform, aimPoint);
bulletDirection = Answers.Directions.FromTo2D(transform, aimPoint);
FromTo2D return Vector2 so if you need Vector3, you might need to cast it.
bulletDirection = (Vector3)Answers.Directions.FromTo2D(transform, aimPoint);
First of all thank you for answering my question! I see, it was simpler than I imagined, I was thinking a bit too difficult again...
Also, Can you explain to me what $$anonymous$$athf.Atan2 does? it's in sentence 24 if you need to look it up again. does it something with float? or does it make you look at a certain angle?
Also, I am a human, at least I think I am ;)
Thank you again for your help and have a nice day,
$$anonymous$$.
Can you explain to me what $$anonymous$$athf.Atan2 does?
It's a basic trigonometry function. For a 2d vector, it gives you the angle in radians of that vector.
If the vector points right, you get 0.
If the vector points up, you get PI/2.
If the vector points left, you get PI or -PI.
If the vector points down, you get -PI / 2.
And everything in between, I mean, yeah it's the angle of the vector from a right vector.
http://docs.unity3d.com/ScriptReference/$$anonymous$$athf.Atan2.html
I recently made a demo which displays radians for another answer you can look at. Although, I convert the result from Atan2 to have absolute radians (no negative radians).
First of all, thanks again for the explanation, it helped me a lot!
I see, I was trying to use the mathf code to get something, and i got somewhere, but now I just need to bind it to some keys (IJ$$anonymous$$L) this is the script I made now:
using UnityEngine;
using System.Collections;
public class AimScript : $$anonymous$$onoBehaviour {
public Transform Playerobject;
public float distance;
public float angle = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
/// <summary>
/// this is the script I made, although it works, I still need to bind them to some keys.
/// So do I need to use the default method, or does it work differently when I am using the mathf?
/// </summary>
void FixedUpdate () {
transform.position = new Vector3(Playerobject.position.x + $$anonymous$$athf.Cos(angle) * distance, Playerobject.position.y + $$anonymous$$athf.Sin(angle) * distance, Playerobject.position.z);
}
}
As you can see I have to add an object in it to connect it. then it will go around my object (in this instance it is still Titus). I can change the position in the inspector, but now I want to control it with my keys on the keyboard(without screwing it up). How can I bind them to the keys I want, and that it works correctly? I already have added an AimHorizontal and AimVertical in the input manager, and gave them the IJ$$anonymous$$L keys. now I want to make it move.
Sorry for not being all that smart.
And thanks again for your help,
$$anonymous$$
Answer by Daniel_Zabojca · Nov 10, 2015 at 10:37 AM
Yep, I got it. Thanks again for the help and the explanation.
I still have to test a few things with the mathf.atan2 before I get it completely, but now I at least know the basics, thanks again @Statement!
Your answer
Follow this Question
Related Questions
Ragdoll Movement Script, Help! 0 Answers
How Do I stop AI Following player on the Y-axis? 0 Answers
2d platformer physics 0 Answers
Unity 5.2.2 2D c# If lever hit then door open. 0 Answers
How do i add a boost,Adding a boost 0 Answers