[英]c# unity2d: How can I move an Object and to change the direction when it collides?
Object 移动,但它没有改变方向,我不知道为什么。
那是名为“zackenblock”的 object 的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class zackenblock_move : MonoBehaviour
{
public static bool col = false;
public float speed = 10f;
// Start is called before the first frame update
void Start()
{
}
void Update()
{
if (zackenblock_col.collosin != col)
{
col = zackenblock_col.collosin;
}
}
// Update is called once per frame
void FixedUpdate()
{
if (col == false){
transform.Translate(Vector3.right * Time.deltaTime * speed);
}
else
{
transform.Translate(Vector3.left * Time.deltaTime * speed);
}
/*if (Input.GetKey(KeyCode.M))
{
col = true;
}*/
}
void OnCollisionEnter(Collision collision){
//Check for a match with the specified name on any GameObject that collides with your GameObject
if (collision.gameObject.name == "Level1_part2")
{
//If the GameObject's name matches the one you suggest, output this message in the console
Debug.Log("Do something here");
col = true;
}
else if (collision.gameObject.name == "Level")
{
//If the GameObject's name matches the one you suggest, output this message in the console
Debug.Log("Do something here");
col = false;
}
}
/*IEnumerator waiter_not_that_waiter_just_waiter(){
yield return new waitforseconds(3f);
//my code here after 3 seconds
transform.Translate(Vector3.right * Time.deltaTime);
yield return new waitforseconds(3f);
transform.Translate(Vector3.left * Time.deltaTime);
}*/
}
这就是 tilemap 中的代码:
using System.Security.Cryptography;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class zackenblock_col : MonoBehaviour
{
public static bool collosin;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.M))
{
collosin = true;
}
}
void OnCollisionEnter(Collision collision){
//Check for a match with the specified name on any GameObject that collides with your GameObject
if (collision.gameObject.name == "zackenblock")
{
//If the GameObject's name matches the one you suggest, output this message in the console
Debug.Log("Do something here");
collosin = true;
}
/*else if (collision.gameObject.name == "Level")
{
//If the GameObject's name matches the one you suggest, output this message in the console
Debug.Log("Do something here");
collosin = false;
}*/
}
}
以下是一些截图:
object 应该向右移动,碰撞时向左移动。
它只会不停地向右移动。
您的代码的主要问题是您拼写错误。 将“collosin”更改为“collision”。 并改变:
void OnCollisionEnter(Collision collision)
进入
void OnCollisionEnter2d(Collision2d collision)
除此之外,您的代码似乎还不错。
使用 OnCollisionEnter2D 因为你正在制作 2D 游戏
private void OnCollisionEnter2D(Collision2D col)
{
}
如果碰撞持续存在,还可以检查 OnCollisionStay2D/exit。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.