Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Enemy pushes player across screen

Discussion in 'Scripting' started by CodeGorilla, Sep 20, 2015.

  1. CodeGorilla

    CodeGorilla

    Joined:
    Sep 15, 2015
    Posts:
    17
    Hi,

    I have my enemy to move to my players position when in range.
    However, when the enemy collides with my player it doesn't stop moving, it pushes the player across the screen.

    This is a 2D game so can't use navmesh, which is super easy.

    I have a box collider for both of them to stop them passing through eachother and a circle collider which is a trigger.

    All it is, is:

    Code (CSharp):
    1. transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);  
    Any suggestions as to how I can do it so the enemy doesn't continuously push the player across the screen?
     
  2. Jana1108

    Jana1108

    Joined:
    Jun 27, 2015
    Posts:
    215
    Try this - you may have to customize it slightly to fit your game.
    Make sure you have these up the top of your code

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    Here is the code - CSharp

    Code (CSharp):
    1. public GameObject enemy;
    2. public GameObject player;  
    3.  
    4. void OnTriggerEnter (Collider other) {
    5.  
    6.         if(other.gameObject.tag == "Player")
    7.         {
    8.                         enemy.transform.position = (X, Y, Z);
    9.                         player.transform.position = (X, Y, Z);
    10.         }
    11.    
    12.     }
    Replace X, Y, and Z with the position of your objects.
     
  3. CodeGorilla

    CodeGorilla

    Joined:
    Sep 15, 2015
    Posts:
    17
    Why do I need to put using UnityEngine.UI?

    Also when the enemy comes to me, I don't need my players position to move. I want him to stay still unless the user moves him.

    I cant set x,y,z values for what you gave me. It only lets me set one value.
     
    Last edited: Sep 20, 2015