- Home /
move toward but keep going
I thought this would be simple but, after hours of research and troubleshooting, I just can't figure out what I'm doing wrong.
I'm trying to make a projectile move toward the position of the player when the projectile is instantiated (the player can move out of the way and the projectile will continue to move in the same direction).
MoveTowards obviously didn't work and none of the other answers I could find did the trick. The projectile just falls straight down.
Here's my code, along with all the stuff I tried but didn't work:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class throwntowardplayer : MonoBehaviour
{
static GameObject S = GameObject.Find("sack");
Vector3 sposition;
Vector3 tposition;
Vector3 direction;
// Start is called before the first frame update
void Start()
{
sposition = S.transform.position;
tposition = transform.position;
direction = (sposition - tposition);
direction.Normalize();
}
// Update is called once per frame
void Update()
{
transform.Translate(direction * 5 * Time.deltaTime);
}
}
//private GameObject Sack = GameObject.Find("sack");
//public Vector3 sackLocation;
//public Vector3 Direction;
//private float speed = 1f;
//private Transform sackTransform;
//private Transform selfTransform;
//sackTransform = Sack.GetComponent<Transform>();
//sackLocation = sackTransform.transform.position;
//selfTransform = GetComponent<Transform>();
//Direction = (sackLocation - selfTransform.transform.position).normalized;
//selfTransform.transform.position += Direction* speed * Time.deltaTime;
//transform.position = Vector3.MoveTowards(transform.position, Sacklocation, .2f);
//transform.Translate(Direction * Time.deltaTime, Space.World);
//transform.position -= transform.forward * Time.deltaTime;
hello, acn you share screen shot of the bullet while in playmode? and debu.log the direction please.
Simply set the forward direction of the projectile to the direction between the enemy and the player like so...
myProjectile.transform.forward = myPlayer.transform.position - myEnemy.transform.position;
Then move the projectile based on its own forward direction...
//projectile code
void fixedUpdate()
{
myProjectileRigidBody.velocity = transform.forward * speed * Time.fixedDeltaTime;
}
Thank you, this seemed to help but now only the rigidbody moves toward the player, no sprite attached. I haven't used rigidbody much. Any suggestions?
GameObject S;
Rigidbody2D twigrigidbody;
// Start is called before the first frame update
void Start()
{
S = GameObject.Find("sack");
twigrigidbody = GetComponent<Rigidbody2D>();
faces();
}
// Update is called once per frame
void Update()
{
flytos();
}
void faces()
{
transform.forward = S.transform.position - transform.position;
}
void flytos()
{
twigrigidbody.velocity = transform.forward * 50 * Time.fixedDeltaTime;
}
}
The rigidbody needs to be attached to the main projectile object, everything else should either be a component or a child of the object.
What happens when you remove the static modifier of 'S' and just initialize it in 'Start'?
Thank you; I had realized that was an issue and corrected it. $$anonymous$$een eye!
No worries. Be sure to subscribe to my YouTube channel https://m.youtube.com/channel/UCo_3O$$anonymous$$EZQiRLQihycbkYd_Q
Answer by Leycarno · Feb 14, 2019 at 01:11 PM
You need transform.LookAt(target) and use AddForce. For the location it could be useful to have a Singleton, to get the player by static method:
using UnityEngine;
public class GlobalSingleton : MonoBehaviour {
[SerializeField] Transform _playerTransform;
static GlobalSingleton _instance;
void Start() {
if (_instance) {
Destroy(gameObject);
}
_instance = this;
}
public static Transform PlayerTransform => _instance._playerTransform;
}
// ----------------------------------------------------------------------------
[RequireComponent(typeof(Rigidbody))]
public class Projectile : MonoBehaviour {
[SerializeField] float _force = 300F;
void OnEnable() {
transform.LookAt(GlobalSingleton.PlayerTransform);
GetComponent<Rigidbody>().AddForce(transform.forward * _force);
}
}
If you seen my previous Answer: Sorry, I've got your question wrong... ^^
No worries; I appreciate your help! Are you saying I should not try your suggestion? I'm unclear what a singleton is; so, I have much researching to do.
Thank you again.
I replaced the wrong answer - so try the code. ;-)
A Singleton is kind of a global object. It exists just once in you scene, if you put the script somewhere - best on an empty. You can use it to add other GameObjects like the player, and than you can get the Reference on the Player whereever you need it, by calling a static method - or a static property, just as I did. $$anonymous$$aybe it's better to write (with the same result):
public static Transform GetPlayerTransform() {
return _instance._playerTransform;
}
The Reason for the singleton is Find - DONT use it, it costs you much of performance.
$$anonymous$$ore important for your Problem, I think, is the use of AddForce, that gives your Game Object a $$anonymous$$ick in a direction. That works by Unity-Physic and is a better way than manipulate the position by yourself.
To explain it all:
[SerializedObject] float _force ist the same as public float _force. It's just a cleaner way to write Code, because you can add Objects by the UnityEditor, but not by other Scripts (by Accident), because the member is private.
[RequireComponent(typeof(Rigidbody))] force unity to add the Rigidbody-Component, wenn you add that Script to the GameObject. It's - again - just nice, so the call of GetComponent can not trow an Error because you forget to add Rigidbody by yourself.
Your answer
Follow this Question
Related Questions
Shoot second cell in 2d 0 Answers
Convert Input.mousePosition to RectTransform pivot position 2 Answers
Cannot change camera position (2D) 1 Answer
Get LookAt vector of a tranform 1 Answer
Resetting a gameobjects position? 1 Answer