Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by theunsigned · Feb 13, 2019 at 07:29 PM · 2dtransformpositiondirectionmovetowards

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;
Comment
Add comment · Show 10
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image xxmariofer · Feb 13, 2019 at 11:10 PM 0
Share

hello, acn you share screen shot of the bullet while in playmode? and debu.log the direction please.

avatar image RobAnthem · Feb 14, 2019 at 02:41 AM 0
Share

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;
 }
avatar image theunsigned RobAnthem · Feb 14, 2019 at 03:18 PM 0
Share

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;
     }
 }
 
avatar image RobAnthem theunsigned · Feb 14, 2019 at 03:29 PM 0
Share

The rigidbody needs to be attached to the main projectile object, everything else should either be a component or a child of the object.

Show more comments
avatar image sean244 · Feb 14, 2019 at 03:33 AM 0
Share

What happens when you remove the static modifier of 'S' and just initialize it in 'Start'?

avatar image theunsigned sean244 · Feb 14, 2019 at 04:12 PM 0
Share

Thank you; I had realized that was an issue and corrected it. $$anonymous$$een eye!

avatar image sean244 theunsigned · Feb 14, 2019 at 05:58 PM 0
Share

No worries. Be sure to subscribe to my YouTube channel https://m.youtube.com/channel/UCo_3O$$anonymous$$EZQiRLQihycbkYd_Q

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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);
     }
 }
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Leycarno · Feb 14, 2019 at 02:48 PM 0
Share

If you seen my previous Answer: Sorry, I've got your question wrong... ^^

avatar image theunsigned Leycarno · Feb 14, 2019 at 03:19 PM 0
Share

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.

avatar image Leycarno theunsigned · Feb 14, 2019 at 08:43 PM 0
Share

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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

236 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges