Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Throw a hook then pull player mechanic not working

Discussion in '2D' started by ELKeshawy, Dec 3, 2022.

  1. ELKeshawy

    ELKeshawy

    Joined:
    Nov 22, 2022
    Posts:
    4
    So basically I want when in range of the boss enemy it throws a dagger that when it hits the player the player movement is stopped for the duration of the hook and pulls the player towards him then the hook detaches after a set time and the player movement is back tried doing it using raycasthit2d but it doesnt react except if im on the right side of the boss and when so it pulls me and the boss and throws us both randomly and aggressively here is the code i used in the script and the script's place is on the boss


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GrapplingHook : MonoBehaviour
    6. {
    7.  
    8.     public LineRenderer lr;
    9.     public LayerMask grappleMask;
    10.     public float moveSpeed = 2;
    11.     public float grappleLength = 5;
    12.     [Min(1)]
    13.     public int maxPoints = 3;
    14.     public float GrappleSpeed;
    15.     public float lineOfSight;
    16.     private Rigidbody2D player;
    17.     public float timer;
    18.     public float maxAttach;
    19.  
    20.     private Rigidbody2D rig;
    21.     private List<Vector2> points = new List<Vector2>();
    22.  
    23.     private void Start()
    24.     {
    25.      
    26.         lr.positionCount = 0;
    27.         player = GameObject.FindGameObjectWithTag("Player").GetComponent<Rigidbody2D>();
    28.         timer = 0;
    29.     }
    30.  
    31.     // Update is called once per frame
    32.     void Update()
    33.     {
    34.         float distanceFromPlayer = Vector2.Distance(player.position, transform.position);
    35.  
    36.  
    37.         Vector2 targetPos = player.position;
    38.         Vector2 direction = Vector2.Lerp(transform.position, targetPos, GrappleSpeed * Time.deltaTime);
    39.  
    40.         if (distanceFromPlayer <= lineOfSight)
    41.         {
    42.  
    43.             RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, grappleLength, grappleMask);
    44.             if (hit.collider != null)
    45.             {
    46.                 Vector2 hitPoint = hit.point;
    47.                 points.Add(hitPoint);
    48.  
    49.                 if (points.Count > maxPoints)
    50.                 {
    51.                     points.RemoveAt(0);
    52.                 }
    53.             }
    54.         }
    55.  
    56.         if (points.Count > 0)
    57.         {
    58.             player.isKinematic = true;
    59.             Vector2 moveFrom = centriod(points.ToArray());
    60.             player.MovePosition(Vector2.MoveTowards(moveFrom, (Vector2)transform.position, Time.deltaTime * moveSpeed));
    61.  
    62.             lr.positionCount = 0;
    63.             lr.positionCount = points.Count * 2;
    64.             for (int n = 0, j = 0; n < points.Count * 2; n += 2, j++)
    65.             {
    66.                 lr.SetPosition(n, transform.position);
    67.                 lr.SetPosition(n + 1, points[j]);
    68.             }
    69.  
    70.          
    71.         }
    72.  
    73.         if (timer >= maxAttach)
    74.         {
    75.             Detatch();
    76.         }
    77.     }
    78.  
    79.     Vector2 centriod(Vector2[] points)
    80.     {
    81.         Vector2 center = Vector2.zero;
    82.         foreach (Vector2 point in points)
    83.         {
    84.             center += point;
    85.         }
    86.         center /= points.Length;
    87.         return center;
    88.     }
    89.  
    90.     public void Detatch()
    91.     {
    92.         timer = 0;
    93.         lr.positionCount = 0;
    94.         points.Clear();
    95.         player.isKinematic = false;
    96.     }
    97.  
    98.  
    99.     private void OnDrawGizmosSelected()
    100.     {
    101.         Gizmos.color = Color.green;
    102.         Gizmos.DrawWireSphere(transform.position, lineOfSight);
    103.         Gizmos.DrawWireSphere(transform.position, grappleLength);
    104.     }
    105.  
    106. }
     
  2. ELKeshawy

    ELKeshawy

    Joined:
    Nov 22, 2022
    Posts:
    4
    I'm still new to using raycasts and overall moving something to something else's position so any help would be appreciated
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,321
    Direction is a direction vector, not a position in the world. Maybe you should look at some basic Vector stuff online to understand the difference?
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    To this end, always use named arguments with
    Physics(2D).Raycast()
    because it contains many poorly-designed overloads:

    https://forum.unity.com/threads/lay...ke-described-in-the-docs.744302/#post-6355392

    Also... try to avoid code like these lines:

    If you have more than one or two dots (.) in a single statement, you're just being mean to yourself.

    How to break down hairy lines of code:

    http://plbm.com/?p=248

    Break it up, practice social distancing in your code, one thing per line please.

    "Programming is hard enough without making it harder for ourselves." - angrypenguin on Unity3D forums

    "Combining a bunch of stuff into one line always feels satisfying, but it's always a PITA to debug." - StarManta on the Unity3D forums

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    When in doubt, print it out!(tm)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.