- Home /
LockOn Target System (c#)
Hey guys,
I'm trying to implement a LockOn-System (i.e. DarkSouls) for my Top-Down Shooter. The camera is static, so there is no need to care about it. I know that you can look at targets with transform.LookAt(target); but I try to get the player not only to face this direction but also to limit its movement to it. So that the player only can move straight to or away from the target or move sideways around it. Can anyone please help me? I'm already struggling with this problem for days...
public float Speed = 5f;
public float JumpHeight = 2f;
public float GroundDistance = 0.2f;
public float DashDistance = 5f;
public LayerMask Ground;
private Rigidbody _body;
private Vector3 _inputs = Vector3.zero;
public bool _isGrounded;
private Transform _groundChecker;
public Animator anim;
const float locomationAnimationSmoothTime = .1f;
public Transform enemy;
void Start()
{
_body = GetComponent<Rigidbody>();
_groundChecker = transform.GetChild(0);
}
void Update()
{
_isGrounded = Physics.Raycast(transform.position, -transform.up, transform.localScale.y + 0.1f);
_inputs = Vector3.zero;
_inputs.x = Input.GetAxis("Horizontal");
_inputs.z = Input.GetAxis("Vertical");
//Animation:
float speedPercent = Input.GetAxis("Vertical");
float speedPercent2 = Input.GetAxis("Horizontal");
anim.SetFloat("Speed", speedPercent, locomationAnimationSmoothTime, Time.deltaTime);
anim.SetFloat("Speed", speedPercent2, locomationAnimationSmoothTime, Time.deltaTime);
if (speedPercent != 0f || speedPercent2 != 0f)
{
anim.SetBool("Laufen", true);
}
else
anim.SetBool("Laufen", false);
if (_inputs != Vector3.zero)
transform.forward = _inputs;
if (Input.GetKeyDown(KeyCode.Z))
{
Debug.Log("watch");
transform.LookAt(enemy);
}
}
void FixedUpdate()
{
_body.MovePosition(_body.position + _inputs * Speed * Time.fixedDeltaTime);
}
}
Answer by hectorux · Nov 06, 2018 at 05:55 PM
Your MovePosition works in a global way, you have to make it local, or make your local behaviour global. For this try this;
_body.MovePosition(transform.position+ transform.forward*Speed*Time.fixedDeltaTime*Input.z+
transform.right*Speed*Time.fixedDeltaTime*Input.x
);
I think you can make it a vector3 first, usually is better to pass a variable instead a calculation
Thanks for your Input! I just found a easy solution which will work for the moment I guess:
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Z))
{
Debug.Log("watch");
lockOnTarget = true;
}
if (lockOnTarget == true)
{
transform.LookAt(enemy);
}